import { PoseLandmarker, FilesetResolver, type PoseLandmarkerResult } from '@mediapipe/tasks-vision'
import type { PoseSettings } from '../types'

const MODEL_BASE = 'https://storage.googleapis.com/mediapipe-models/pose_landmarker'

/** Raw result from MediaPipe — preserves original types for DrawingUtils compatibility. */
export type PoseResult = PoseLandmarkerResult

export class PoseDetector {
  private landmarker: PoseLandmarker
  private constructor(landmarker: PoseLandmarker) {
    this.landmarker = landmarker
  }

  static async create(settings: PoseSettings): Promise<PoseDetector> {
    const vision = await FilesetResolver.forVisionTasks(
      'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm'
    )

    const landmarker = await PoseLandmarker.createFromOptions(vision, {
      baseOptions: {
        modelAssetPath: `${MODEL_BASE}/${settings.model}/float16/1/${settings.model}.task`,
        delegate: settings.delegate,
      },
      runningMode: 'VIDEO',
      numPoses: settings.numPoses,
      minPoseDetectionConfidence: settings.minDetectionConfidence,
      minTrackingConfidence: settings.minTrackingConfidence,
      minPosePresenceConfidence: settings.minPresenceConfidence,
    })

    return new PoseDetector(landmarker)
  }

  detectFrame(video: HTMLVideoElement, timestamp: number): PoseResult {
    return this.landmarker.detectForVideo(video, timestamp)
  }

  dispose(): void {
    this.landmarker.close()
  }
}
