use anyhow::Result;
use sqlx::postgres::PgPoolOptions;

#[tokio::main]
async fn main() -> Result<()> {
    // Database connection
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres://accusys@localhost:5432/momentry")
        .await?;

    let video_uuid = "9760d0820f0cf9a7";
    let video_id = 28;
    let video_path = "/Users/accusys/momentry/var/sftpgo/data/demo/ExaSAN PCIe series - Director Ou Yu-Zhi Shares His Experience.mp4";

    println!("Creating monitor job for video:");
    println!("  UUID: {}", video_uuid);
    println!("  ID: {}", video_id);
    println!("  Path: {}", video_path);

    // 1. Create monitor job
    let job_row = sqlx::query(
        r#"
        INSERT INTO monitor_jobs (uuid, video_path, status)
        VALUES ($1, $2, 'pending')
        RETURNING id, uuid, video_path, status
        "#
    )
    .bind(video_uuid)
    .bind(video_path)
    .fetch_one(&pool)
    .await?;

    let job_id: i32 = job_row.get(0);
    let job_uuid: String = job_row.get(1);
    let job_status: String = job_row.get(3);

    println!("\nCreated monitor job:");
    println!("  Job ID: {}", job_id);
    println!("  Job UUID: {}", job_uuid);
    println!("  Status: {}", job_status);

    // 2. Update video with job_id
    sqlx::query(
        r#"
        UPDATE videos 
        SET job_id = $1, updated_at = CURRENT_TIMESTAMP 
        WHERE id = $2
        "#
    )
    .bind(job_id)
    .bind(video_id)
    .execute(&pool)
    .await?;

    println!("Updated video {} with job_id {}", video_id, job_id);

    // 3. Update monitor_jobs with video_id
    sqlx::query(
        r#"
        UPDATE monitor_jobs 
        SET video_id = $1, updated_at = CURRENT_TIMESTAMP 
        WHERE id = $2
        "#
    )
    .bind(video_id)
    .bind(job_id)
    .execute(&pool)
    .await?;

    println!("Updated monitor_jobs {} with video_id {}", job_id, video_id);

    // 4. Create processor results for this job
    let processors = vec!["asr", "cut", "yolo", "ocr", "face", "pose", "asrx"];
    
    for processor in processors {
        sqlx::query(
            r#"
            INSERT INTO processor_results (job_id, video_id, processor, status)
            VALUES ($1, $2, $3, 'pending')
            ON CONFLICT (job_id, processor) DO NOTHING
            "#
        )
        .bind(job_id)
        .bind(video_id)
        .bind(processor)
        .execute(&pool)
        .await?;

        println!("Created processor result for {}: {}", processor, job_id);
    }

    println!("\n✅ Job creation completed successfully!");
    println!("Job ID: {}", job_id);
    println!("The worker should now pick up this job and start processing.");

    Ok(())
}
