use anyhow::Result;
use momentry_core::core::config;
use momentry_core::core::db::PostgresDb;
use momentry_core::core::processor::asrx::AsrxResult;
use momentry_core::core::processor::face::FaceResult;
use momentry_core::core::processor::ocr::OcrResult;
use momentry_core::core::processor::pose::PoseResult;
use momentry_core::core::processor::yolo::{YoloPythonResult, YoloResult};
use momentry_core::worker::processor::ProcessorPool;
use serde_json;
use std::fs;

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize tracing
    tracing_subscriber::fmt::init();

    // Database connection
    let db_url = config::DATABASE_URL.clone();
    let db = PostgresDb::new(&db_url).await?;

    let uuid = "9760d0820f0cf9a7";

    // Load OCR result
    let ocr_json =
        fs::read_to_string("/Users/accusys/momentry/output/job_2_ocr_1774475908877.json")?;
    let ocr_result: OcrResult = serde_json::from_str(&ocr_json)?;
    println!("Loaded OCR result with {} frames", ocr_result.frames.len());

    // Load FACE result
    let face_json =
        fs::read_to_string("/Users/accusys/momentry/output/job_2_face_1774475908878.json")?;
    let face_result: FaceResult = serde_json::from_str(&face_json)?;
    println!(
        "Loaded FACE result with {} frames",
        face_result.frames.len()
    );

    // Load POSE result
    let pose_json =
        fs::read_to_string("/Users/accusys/momentry/output/job_2_pose_1774475908880.json")?;
    let pose_result: PoseResult = serde_json::from_str(&pose_json)?;
    println!(
        "Loaded POSE result with {} frames",
        pose_result.frames.len()
    );

    // Load ASRX result
    let asrx_json =
        fs::read_to_string("/Users/accusys/momentry/output/job_2_asrx_1774475908887.json")?;
    let asrx_result: AsrxResult = serde_json::from_str(&asrx_json)?;
    println!(
        "Loaded ASRX result with {} segments",
        asrx_result.segments.len()
    );

    // Load YOLO result
    let yolo_json =
        fs::read_to_string("/Users/accusys/momentry/output/job_2_yolo_1774475908875.json")?;
    let python_result: YoloPythonResult = serde_json::from_str(&yolo_json)?;
    let yolo_result = python_result.to_yolo_result();
    println!(
        "Loaded YOLO result with {} frames",
        yolo_result.frames.len()
    );

    // Store chunks using ProcessorPool's static methods
    println!("Storing OCR chunks...");
    ProcessorPool::store_ocr_chunks(&db, uuid, &ocr_result).await?;
    println!("Storing FACE chunks...");
    ProcessorPool::store_face_chunks(&db, uuid, &face_result).await?;
    println!("Storing POSE chunks...");
    ProcessorPool::store_pose_chunks(&db, uuid, &pose_result).await?;
    println!("Storing ASRX chunks...");
    ProcessorPool::store_asrx_chunks(&db, uuid, &asrx_result).await?;
    println!("Storing YOLO chunks...");
    ProcessorPool::store_yolo_chunks(&db, uuid, &yolo_result).await?;

    println!("All trace chunks stored successfully!");

    Ok(())
}
