use anyhow::{Context, Result};
use serde::Deserialize;
use std::path::Path;
use tracing::{info, warn};

use crate::core::db::PostgresDb;

#[derive(Debug, Deserialize)]
pub struct CastEntry {
    pub name: String,
    pub role: String,
    pub image: Option<String>,
}

/// Ingests TMDB cast data from the JSON file generated by `tmdb_cast_fetcher.py`
pub async fn ingest_cast(db: &PostgresDb, json_path: &str) -> Result<usize> {
    let path = Path::new(json_path);
    if !path.exists() {
        return Err(anyhow::anyhow!("Cast JSON file not found: {}", json_path));
    }

    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read cast JSON: {}", json_path))?;

    let cast_list: Vec<CastEntry> =
        serde_json::from_str(&content).with_context(|| "Invalid cast JSON format")?;

    let mut count = 0;
    for entry in &cast_list {
        match db.get_or_create_identity(&entry.name).await {
            Ok(_talent) => {
                info!("Ingested TMDB cast: {} as {}", entry.name, entry.role);
                count += 1;
            }
            Err(e) => warn!("Failed to create talent '{}': {}", entry.name, e),
        }
    }

    Ok(count)
}
