import { Landmark } from "../hooks/usePoseDetection";

/**
 * Calculate similarity score between two sets of landmarks.
 * Returns a score from 0-100, where 100 is a perfect match.
 * Works with MediaPipe's 33 keypoints format.
 */
export function calculateSimilarityScore(
  referenceLandmarks: Landmark[],
  currentLandmarks: Landmark[]
): number {
  if (!referenceLandmarks || !currentLandmarks) {
    return 0;
  }

  // Focus on body landmarks (indices 11-28: shoulders, elbows, wrists, hips, knees, ankles)
  // Skip face landmarks (0-10) and foot details (29-32) for more stable comparison
  const bodyIndices = Array.from({ length: 18 }, (_, i) => i + 11); // 11-28

  let totalDistance = 0;
  let validPoints = 0;

  for (const idx of bodyIndices) {
    if (idx >= referenceLandmarks.length || idx >= currentLandmarks.length) {
      continue;
    }

    const refLm = referenceLandmarks[idx];
    const currLm = currentLandmarks[idx];

    // Only compare if both landmarks are visible enough
    if (
      !refLm ||
      !currLm ||
      refLm.visibility < 0.5 ||
      currLm.visibility < 0.5
    ) {
      continue;
    }

    // Calculate Euclidean distance (using x, y coordinates)
    const distance = Math.sqrt(
      Math.pow(refLm.x - currLm.x, 2) + Math.pow(refLm.y - currLm.y, 2)
    );

    totalDistance += distance;
    validPoints++;
  }

  if (validPoints === 0) {
    return 0;
  }

  // Calculate average distance
  const avgDistance = totalDistance / validPoints;

  // Convert distance to similarity score (more generous)
  // Distance of 0 = 100 score, distance of 1.0 or more = 0 score
  // Increased from 0.5 to 1.0 to give users a bigger margin of error
  const similarity = Math.max(0, 100 * (1 - avgDistance / 1.0));

  return Math.round(similarity * 100) / 100; // Round to 2 decimal places
}
