use std::process::Command;

fn skip_heavy_blackbox_test() -> bool {
    std::env::var_os("RPKI_SKIP_HEAVY_BLACKBOX_TESTS").is_some()
}

#[test]
fn cli_payload_replay_root_only_smoke_writes_report_json() {
    if skip_heavy_blackbox_test() {
        return;
    }
    let bin = env!("CARGO_BIN_EXE_rpki");
    let db_dir = tempfile::tempdir().expect("db tempdir");
    let out_dir = tempfile::tempdir().expect("out tempdir");
    let report_path = out_dir.path().join("report.json");

    let tal_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/tal/apnic-rfc7730-https.tal");
    let ta_path =
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ta/apnic-ta.cer");
    let archive_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target/live/payload_replay/payload-archive");
    let locks_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target/live/payload_replay/locks.json");

    if !archive_root.is_dir() || !locks_path.is_file() {
        eprintln!(
            "skipping cli payload replay smoke; missing fixtures: archive={} locks={}",
            archive_root.display(),
            locks_path.display()
        );
        return;
    }

    let out = Command::new(bin)
        .args([
            "--db",
            db_dir.path().to_string_lossy().as_ref(),
            "--tal-path",
            tal_path.to_string_lossy().as_ref(),
            "--ta-path",
            ta_path.to_string_lossy().as_ref(),
            "--payload-replay-archive",
            archive_root.to_string_lossy().as_ref(),
            "--payload-replay-locks",
            locks_path.to_string_lossy().as_ref(),
            "--validation-time",
            "2026-03-13T02:30:00Z",
            "--max-depth",
            "0",
            "--max-instances",
            "1",
            "--report-json",
            report_path.to_string_lossy().as_ref(),
        ])
        .output()
        .expect("run replay cli");

    assert!(
        out.status.success(),
        "cli failed: status={}\nstdout={}\nstderr={}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );

    let bytes = std::fs::read(&report_path).expect("read report json");
    let v: serde_json::Value = serde_json::from_slice(&bytes).expect("parse report json");
    assert_eq!(v["format_version"], 2);
    assert!(v["tree"]["instances_processed"].as_u64().unwrap_or(0) >= 1);
    assert!(v.get("publication_points").is_some());
    assert!(v.get("downloads").is_some());
    assert!(v.get("download_stats").is_some());
}
