use std::process::Command;

#[test]
fn cli_offline_smoke_writes_report_json() {
    let bin = env!("CARGO_BIN_EXE_rpki");

    let db_dir = tempfile::tempdir().expect("db tempdir");
    let repo_dir = tempfile::tempdir().expect("repo 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 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(),
            "--rsync-local-dir",
            repo_dir.path().to_string_lossy().as_ref(),
            "--max-depth",
            "0",
            "--max-instances",
            "1",
            "--report-json",
            report_path.to_string_lossy().as_ref(),
        ])
        .output()
        .expect("run 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.get("policy").is_some());
    assert!(v.get("tree").is_some());
    assert!(v.get("publication_points").is_some());
    assert!(v.get("vrps").is_some());
    assert!(v.get("aspas").is_some());
    assert!(v.get("downloads").is_some());
    assert!(v.get("download_stats").is_some());
}
