//! Caption generation 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 Caption module
pub async fn process_caption_module(
    caption_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::Caption).start(1);
    }

    let caption_result = momentry_core::core::processor::process_caption(
        video_path,
        caption_path.to_str().unwrap(),
        Some(uuid),
    )
    .await?;

    let caption_json = serde_json::to_string_pretty(&caption_result)?;
    std::fs::write(caption_path, &caption_json)?;

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

    println!("  ✓ Caption saved: {} frames", caption_result.total_frames);

    {
        let mut state = progress_state.lock().unwrap();
        state
            .get_processor(ProcessorType::Caption)
            .complete(&format!("{} frames", caption_result.total_frames));
    }

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

    Ok(())
}
