//! OCR (Optical Character 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 OCR module
pub async fn process_ocr_module(
    ocr_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::Ocr).start(1);
    }

    let ocr_result = momentry_core::core::processor::process_ocr(
        video_path,
        ocr_path.to_str().unwrap(),
        Some(uuid),
    )
    .await?;

    let ocr_json = serde_json::to_string_pretty(&ocr_result)?;
    std::fs::write(ocr_path, &ocr_json)?;

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

    println!(
        "  ✓ OCR saved: {} frames with text",
        ocr_result.frames.len()
    );

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

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

    Ok(())
}
