import { KEEP_INDICES } from '../components/RecordingPlayer'

interface RawFrame {
  t: number
  landmarks: { x: number; y: number; visibility?: number }[]
  worldLandmarks: { x: number; y: number; z: number; visibility?: number }[]
}

interface SimplifiedFrame {
  t: number
  landmarks: { x: number; y: number; visibility?: number }[]
  worldLandmarks: { x: number; y: number; z: number; visibility?: number }[]
}

/**
 * Simplify a full 33-landmark recording to the 13 stick-figure landmarks.
 * Optionally deduplicates frames by 2D movement threshold (average landmark distance).
 */
export function simplifyRecording(
  frames: RawFrame[],
  options: { movementThreshold?: number; trimEndMs?: number } = {},
): SimplifiedFrame[] {
  const { movementThreshold = 0, trimEndMs = 0 } = options

  let result = frames

  // Trim end
  if (trimEndMs > 0 && result.length > 0) {
    const cutoff = result[result.length - 1].t - trimEndMs
    result = result.filter(f => f.t <= cutoff)
  }

  // Pick only the landmarks we need
  const simplified = result.map(f => ({
    t: f.t,
    landmarks: KEEP_INDICES.map(i => f.landmarks[i]),
    worldLandmarks: KEEP_INDICES.map(i => f.worldLandmarks[i]),
  }))

  // Deduplicate by movement
  if (movementThreshold > 0 && simplified.length > 1) {
    const kept = [simplified[0]]
    for (let i = 1; i < simplified.length; i++) {
      const prev = kept[kept.length - 1].landmarks
      const curr = simplified[i].landmarks
      let sum = 0
      for (let j = 0; j < curr.length; j++) {
        const dx = curr[j].x - prev[j].x
        const dy = curr[j].y - prev[j].y
        sum += Math.sqrt(dx * dx + dy * dy)
      }
      if (sum / curr.length >= movementThreshold) {
        kept.push(simplified[i])
      }
    }
    // Always keep last frame
    if (kept[kept.length - 1] !== simplified[simplified.length - 1]) {
      kept.push(simplified[simplified.length - 1])
    }
    return kept
  }

  return simplified
}
