//! ASR (Automatic Speech 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 ASR module
pub async fn process_asr_module(
    asr_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::Asr).start(1);
    }

    let asr_result = momentry_core::core::processor::process_asr(
        video_path,
        asr_path.to_str().unwrap(),
        Some(uuid),
    )
    .await?;

    let asr_json = serde_json::to_string_pretty(&asr_result)?;
    std::fs::write(asr_path, &asr_json)?;

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

    println!("  ✓ ASR saved: {} segments", asr_result.segments.len());

    {
        let mut state = progress_state.lock().unwrap();
        state
            .get_processor(ProcessorType::Asr)
            .complete(&format!("{} segments", asr_result.segments.len()));
    }

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

    Ok(())
}
