import { FaceLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';

export const cameraInput = {
  left: false,
  right: false,
  active: false,
  zone: 'center'
};

let video;
let faceLandmarker;
let lastTime = 0;

const DETECTION_INTERVAL = 60;

export async function initCameraControl() {
  if (cameraInput.active) 
    return video;

  video = document.createElement('video');
  video.autoplay = true;
  video.playsInline = true;
  video.muted = true;

  // Set low resolution and frame rate for better performance
  const stream = await navigator.mediaDevices.getUserMedia({
    video: {
      width: { ideal: 160 },
      height: { ideal: 120 },
      frameRate: { ideal: 30 }
    }
  });

  video.srcObject = stream;

  //load models for face landmark detection
  const vision = await FilesetResolver.forVisionTasks(
    'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision/wasm'
  );
  faceLandmarker = await FaceLandmarker.createFromOptions(vision, {
    baseOptions: {
      modelAssetPath:
        'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/latest/face_landmarker.task',
    },
    runningMode: 'VIDEO',
    numFaces: 1
  });

  cameraInput.active = true;
  return video;
}

export function updateCameraControl() {
  const now = performance.now();

  // Limit detection frequency to improve performance
  if (now - lastTime < DETECTION_INTERVAL) 
    return;
  lastTime = now;

  if (!faceLandmarker || !video || video.readyState < 2) 
    return;

  const result = faceLandmarker.detectForVideo(video, now);

  // If no face is detected, reset to center
  if (!result.faceLandmarks.length) {
    cameraInput.left = false;
    cameraInput.right = false;
    cameraInput.zone = 'center';
    return;
  }

  // look at the nose and determine zone
  const x = result.faceLandmarks[0][1].x;
  if (x < 0.4) {
    cameraInput.left = false;
    cameraInput.right = true;
    cameraInput.zone = 'right';
  } else if (x > 0.6) {
    cameraInput.left = true;
    cameraInput.right = false;
    cameraInput.zone = 'left';
  } else {
    cameraInput.left = false;
    cameraInput.right = false;
    cameraInput.zone = 'center';
  }
}