//! Face detection and recognition 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 Face module
pub async fn process_face_module(
    face_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::Face).start(1);
    }

    let face_result = momentry_core::core::processor::process_face(
        video_path,
        face_path.to_str().unwrap(),
        Some(uuid),
    )
    .await?;

    let face_json = serde_json::to_string_pretty(&face_result)?;
    std::fs::write(face_path, &face_json)?;

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

    println!("  ✓ Face saved: {} frames", face_result.frames.len());

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

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

    Ok(())
}
