//! Pose estimation processing module

use anyhow::Result;
use momentry_core::ui::progress::{ProcessorType, ProgressState, ProgressUi};
use momentry_core::OutputDir;
use std::path::Path;
use std::sync::{Arc, Mutex};

/// Process Pose module
pub async fn process_pose_module(
    pose_path: &Path,
    video_path: &str,
    uuid: &str,
    progress_state: &Arc<Mutex<ProgressState>>,
    ui: &Arc<Mutex<Option<ProgressUi>>>,
) -> Result<()> {
    {
        let mut state = progress_state.lock().unwrap();
        state.get_processor(ProcessorType::Pose).start(1);
    }

    let pose_result = momentry_core::core::processor::process_pose(
        video_path,
        pose_path.to_str().unwrap(),
        Some(uuid),
    )
    .await?;

    let pose_json = serde_json::to_string_pretty(&pose_result)?;
    std::fs::write(pose_path, &pose_json)?;

    let output_dir = OutputDir::new();
    let _ = output_dir.backup_file(uuid, "pose.json");

    println!("  ✓ Pose saved: {} frames", pose_result.frames.len());

    {
        let mut state = progress_state.lock().unwrap();
        state
            .get_processor(ProcessorType::Pose)
            .complete(&format!("{} frames", pose_result.frames.len()));
        state.stop();
    }

    if let Some(ref mut ui) = *ui.lock().unwrap() {
        let _ = ui.render();
    }

    Ok(())
}
