// ML-based panel detection using COCO-SSD pre-trained model

interface Panel {
  id: string;
  x: number;
  y: number;
  width: number;
  height: number;
  reading_order: number;
}

let model: any = null;
let tfLoaded = false;

async function loadTF(): Promise<void> {
  if (tfLoaded) return;

  // Load TensorFlow.js
  await import("@tensorflow/tfjs");
  tfLoaded = true;
}

async function loadModel(): Promise<void> {
  if (model) return;

  await loadTF();

  // Load COCO-SSD model (pre-trained on millions of images)
  const cocoSsd = await import("@tensorflow-models/coco-ssd");
  model = await cocoSsd.load({
    base: "lite_mobilenet_v2", // Smaller, faster model
  });
}

async function detectPanelsML(imageData: ImageData): Promise<Panel[]> {
  await loadModel();

  // Create HTMLCanvasElement to run model inference
  const canvas = document.createElement("canvas");
  canvas.width = imageData.width;
  canvas.height = imageData.height;
  const ctx = canvas.getContext("2d")!;
  ctx.putImageData(imageData, 0, 0);

  // Run COCO-SSD model
  const predictions = await model.detect(canvas);

  // Filter predictions to find rectangular regions (panels)
  // COCO-SSD detects common objects, we look for rectangular ones
  const panels: Panel[] = [];
  const imgWidth = imageData.width;
  const imgHeight = imageData.height;

  for (let i = 0; i < predictions.length; i++) {
    const pred = predictions[i];

    // COCO-SSD detects "book" and similar objects
    // We filter for reasonable panel-like detections
    const [x, y, w, h] = pred.bbox;
    const aspectRatio = w / h;

    const isRectangular =
      aspectRatio > 0.3 && // Not too tall/thin
      aspectRatio < 5 && // Not too wide
      w > imgWidth * 0.05 && // Not too small
      h > imgHeight * 0.05;

    if (isRectangular) {
      panels.push({
        id: `ml-panel-${i}`,
        x: (x / imgWidth) * 100,
        y: (y / imgHeight) * 100,
        width: (w / imgWidth) * 100,
        height: (h / imgHeight) * 100,
        reading_order: i,
      });
    }
  }

  // Sort panels by reading order
  panels.sort((a, b) => {
    const rowA = Math.floor(a.y / 25);
    const rowB = Math.floor(b.y / 25);
    if (rowA !== rowB) return rowA - rowB;
    return a.x - b.x;
  });

  panels.forEach((p, i) => (p.reading_order = i));

  return panels;
}

export { detectPanelsML, loadModel };
