// Oppsummerings-dispatcher — delegerer til synops-summarize CLI.
//
// Maskinrommet orkestrerer, CLI-verktøyet gjør jobben.
// Ref: docs/retninger/unix_filosofi.md
//
// Jobbtype: "summarize_communication"
// Payload: { "communication_id": "<uuid>", "requested_by": "<uuid>" }

use uuid::Uuid;

use crate::ai_admin;
use crate::cli_dispatch;
use crate::jobs::JobRow;

/// Synops-summarize binary path.
/// Søker i PATH, men kan overrides med SYNOPS_SUMMARIZE_BIN.
fn summarize_bin() -> String {
    std::env::var("SYNOPS_SUMMARIZE_BIN")
        .unwrap_or_else(|_| "synops-summarize".to_string())
}

/// Handler for summarize_communication-jobber.
///
/// Spawner synops-summarize med --write for å gjøre alt arbeidet:
/// LLM-kall, node-opprettelse, edge-skriving, ressurslogging.
///
/// Payload forventer:
///   - communication_id: UUID — kommunikasjonsnoden som skal oppsummeres
///   - requested_by: UUID — brukeren som utløste oppsummeringen
pub async fn handle_summarize_communication(
    job: &JobRow,
    db: &sqlx::PgPool,
) -> Result<serde_json::Value, String> {
    let communication_id: Uuid = job
        .payload
        .get("communication_id")
        .and_then(|v| v.as_str())
        .and_then(|s| s.parse().ok())
        .ok_or("Mangler gyldig communication_id i payload")?;

    let requested_by: Uuid = job
        .payload
        .get("requested_by")
        .and_then(|v| v.as_str())
        .and_then(|s| s.parse().ok())
        .ok_or("Mangler gyldig requested_by i payload")?;

    // Bygg kommando
    let bin = summarize_bin();
    let mut cmd = tokio::process::Command::new(&bin);

    cmd.arg("--communication-id")
        .arg(communication_id.to_string())
        .arg("--requested-by")
        .arg(requested_by.to_string())
        .arg("--write");

    // Sett miljøvariabler CLI-verktøyet trenger
    cli_dispatch::set_database_url(&mut cmd)?;
    cli_dispatch::forward_env(&mut cmd, "AI_GATEWAY_URL");
    cli_dispatch::forward_env(&mut cmd, "LITELLM_MASTER_KEY");

    // Modellalias fra ai_job_routing — admin kan endre uten redeploy
    let model_alias = ai_admin::resolve_routing_or_default(db, "summarize").await;
    cmd.env("AI_SUMMARY_MODEL", &model_alias);

    tracing::info!(
        communication_id = %communication_id,
        requested_by = %requested_by,
        bin = %bin,
        "Starter synops-summarize"
    );

    let result = cli_dispatch::run_cli_tool(&bin, &mut cmd).await?;

    tracing::info!(
        communication_id = %communication_id,
        summary_node_id = result["summary_node_id"].as_str().unwrap_or("n/a"),
        status = result["status"].as_str().unwrap_or("unknown"),
        "synops-summarize fullført"
    );

    Ok(result)
}
