#!/usr/bin/env python3
"""Smoke-test the bundled MediaPipe model against one NEXT11 source image."""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

import cv2
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--model",
        type=Path,
        default=Path(__file__).resolve().parent / "models/pose_landmarker_full.task",
    )
    parser.add_argument(
        "--image",
        type=Path,
        default=Path(__file__).resolve().parent
        / "external_pose_images_dynamic_warmup_v83_strict_no_reuse"
        / "high-knee-tuck"
        / "02_left_knee_tuck_peak.jpg",
    )
    args = parser.parse_args()

    image_bgr = cv2.imread(str(args.image))
    if image_bgr is None:
        raise FileNotFoundError(args.image)
    image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
    mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image_rgb)

    options = vision.PoseLandmarkerOptions(
        base_options=python.BaseOptions(
            model_asset_path=str(args.model),
            delegate=python.BaseOptions.Delegate.CPU,
        ),
        running_mode=vision.RunningMode.IMAGE,
    )
    with vision.PoseLandmarker.create_from_options(options) as landmarker:
        result = landmarker.detect(mp_image)

    pose_count = len(result.pose_landmarks)
    landmark_count = len(result.pose_landmarks[0]) if pose_count else 0
    world_count = len(result.pose_world_landmarks[0]) if result.pose_world_landmarks else 0
    mean_visibility = (
        sum(point.visibility for point in result.pose_landmarks[0]) / landmark_count
        if landmark_count
        else 0.0
    )
    passed = pose_count == 1 and landmark_count == 33 and world_count == 33
    print(
        json.dumps(
            {
                "pass": passed,
                "mediapipe": mp.__version__,
                "opencv": cv2.__version__,
                "poseCount": pose_count,
                "landmarkCount": landmark_count,
                "worldLandmarkCount": world_count,
                "meanVisibility": round(mean_visibility, 6),
                "model": str(args.model),
                "image": str(args.image),
            },
            separators=(",", ":"),
        ),
        flush=True,
    )
    return 0 if passed else 1


if __name__ == "__main__":
    exit_code = main()
    # Some MediaPipe native delegates keep non-daemon worker threads alive after
    # a successful one-shot image run. This smoke test owns its process, so a
    # hard process exit is intentional and keeps CI/headless runs deterministic.
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(exit_code)
