#[path = "../support/utils.rs"]
mod _utils;

use _utils::{boxed_error, cleanup_run, create_client, new_run_id, print_summary, require};
use mubit_sdk::TransportMode;
use serde_json::{json, Value};
use std::error::Error;
use std::time::Instant;
use tokio::time::{sleep, Duration};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn Error>> {
    let name = "internal_control_ingest_batch_job_lifecycle";
    let started = Instant::now();
    let client = create_client().await?;
    let run_id = new_run_id("internal_control_ingest_batch");
    client.set_run_id(Some(run_id.clone()));
    client.set_transport(TransportMode::Http);
    let mut passed = true;
    let mut detail = "validated raw control ingest and batch lifecycle".to_string();
    let mut metrics = json!({});

    let scenario = async {
        let accepted = client.control.ingest(json!({
            "run_id": run_id,
            "agent_id": "rust-sdk-example",
            "parallel": false,
            "items": [{
                "item_id": "incident-1",
                "content_type": "text",
                "text": "Incident SEV2-7314: cache warmer rollback restored baseline latency.",
                "payload_json": "",
                "hints_json": "{\"priority\":\"high\"}",
                "metadata_json": "{\"source\":\"ops-incident\"}"
            }]
        })).await?;
        let job_id = accepted.get("job_id").and_then(Value::as_str).ok_or_else(|| boxed_error(format!("ingest did not return job_id: {accepted}")))?.to_string();

        let mut job: Option<Value> = None;
        for _ in 0..60 {
            let current = client.control.get_ingest_job(json!({"run_id": run_id, "job_id": job_id})).await?;
            if current.get("done").and_then(Value::as_bool).unwrap_or(false) { job = Some(current); break; }
            sleep(Duration::from_millis(250)).await;
        }
        let job = job.ok_or_else(|| boxed_error("timeout waiting for ingest job completion"))?;

        let batch = client.control.batch_insert(json!({
            "run_id": run_id,
            "deduplicate": true,
            "items": [
                {"item_id": "batch-1", "text": "Release checkpoint reduced p95 latency.", "metadata_json": "{\"source\":\"release\"}", "source": "rust-sdk-batch", "embedding": []},
                {"item_id": "batch-2", "text": "Warehouse QA hold can be released after clean cycles.", "metadata_json": "{\"source\":\"warehouse\"}", "source": "rust-sdk-batch", "embedding": []}
            ]
        })).await?;

        require(job.get("status").and_then(Value::as_str) == Some("completed"), format!("job should be completed: {job}"))?;
        require(batch.get("count").and_then(Value::as_u64).unwrap_or(0) >= 2, format!("expected batch inserts: {batch}"))?;

        metrics = json!({"run_id": run_id, "job_id": job_id, "batch_count": batch.get("count").cloned().unwrap_or(Value::Null)});
        Ok::<(), Box<dyn Error>>(())
    }.await;

    if let Err(err) = scenario { passed = false; detail = err.to_string(); }
    let cleanup_ok = cleanup_run(&client, &run_id).await;
    if !cleanup_ok { passed = false; detail = format!("{detail} | cleanup failures"); }
    print_summary(name, passed, &detail, &metrics, started.elapsed().as_secs_f64(), cleanup_ok);
    if passed { Ok(()) } else { Err(boxed_error(detail)) }
}
