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_delta_replay_rejects_wrong_base_locks() {
    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 wrong_base_locks = out_dir.path().join("wrong-base-locks.json");
    std::fs::write(&wrong_base_locks, b"wrong-base-locks").expect("write wrong base locks");

    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 demo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target/live/apnic_delta_demo/20260315-170223-autoplay");
    let base_archive = demo_root.join("base-payload-archive");
    let delta_archive = demo_root.join("payload-delta-archive");
    let delta_locks = demo_root.join("locks-delta.json");

    if !base_archive.is_dir() || !delta_archive.is_dir() || !delta_locks.is_file() {
        eprintln!(
            "skipping cli delta replay smoke; missing fixtures: base_archive={} delta_archive={} delta_locks={}",
            base_archive.display(),
            delta_archive.display(),
            delta_locks.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-base-archive",
            base_archive.to_string_lossy().as_ref(),
            "--payload-base-locks",
            wrong_base_locks.to_string_lossy().as_ref(),
            "--payload-delta-archive",
            delta_archive.to_string_lossy().as_ref(),
            "--payload-delta-locks",
            delta_locks.to_string_lossy().as_ref(),
            "--validation-time",
            "2026-03-15T10:00:00Z",
            "--max-depth",
            "0",
            "--max-instances",
            "1",
            "--report-json",
            report_path.to_string_lossy().as_ref(),
        ])
        .output()
        .expect("run delta replay cli");

    assert_eq!(out.status.code(), Some(2), "status={}", out.status);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("base locks sha256 mismatch")
            || stderr.contains("payload replay setup failed"),
        "stderr={stderr}"
    );
}
