use metacrate_grid_agent::{CONFIG_SCHEMA_VERSION, ConfigLoader};
use serde_yaml_ng::Value;
use std::fs;
use std::path::{Path, PathBuf};

fn workspace() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("workspace")
        .to_path_buf()
}

#[test]
fn examples_are_versioned_placeholder_only_and_offline_validation_has_no_io_peer() {
    let root = workspace();
    for name in [
        "grid-agent.example.yml",
        "grid-agent.integrated.example.yml",
        "grid-agent.split.example.yml",
    ] {
        let bytes = fs::read(root.join("config").join(name)).expect("example");
        let value: Value = serde_yaml_ng::from_slice(&bytes).expect("valid YAML");
        assert_eq!(
            value["schema_version"].as_u64(),
            Some(u64::from(CONFIG_SCHEMA_VERSION))
        );
        let text = String::from_utf8(bytes).unwrap();
        for forbidden in ["Bearer ", "sk-", "password123", "SECRET_CANARY"] {
            assert!(!text.contains(forbidden), "{name} contains {forbidden}");
        }
    }
    let offline = root.join("config/grid-agent.example.yml");
    let config = ConfigLoader::new().with_file(offline).load().unwrap();
    assert!(config.grid.is_none());
}

#[test]
fn service_and_installers_preserve_state_secrets_and_graceful_shutdown() {
    let root = workspace();
    let unit = fs::read_to_string(
        root.join("packaging/metacrate-grid-agent/systemd/metacrate-grid-agent.service"),
    )
    .unwrap();
    for required in [
        "ExecStartPre=",
        "--check-config",
        "KillSignal=SIGINT",
        "ProtectSystem=strict",
        "NoNewPrivileges=true",
        "ReadWritePaths=/var/lib/metacrate/grid-agent",
        "/etc/metacrate/config.yml",
    ] {
        assert!(unit.contains(required), "unit lacks {required}");
    }
    for forbidden in ["API_KEY=", "PASSWORD=", "TOKEN=", "EnvironmentFile="] {
        assert!(!unit.contains(forbidden), "unit embeds {forbidden}");
    }
    let shell = fs::read_to_string(root.join("packaging/metacrate-grid-agent/install.sh")).unwrap();
    let powershell =
        fs::read_to_string(root.join("packaging/metacrate-grid-agent/install.ps1")).unwrap();
    assert!(shell.contains("metacrate-grid-agent.new"));
    assert!(powershell.contains("metacrate-grid-agent.new.exe"));
    for forbidden in ["grid-agent.json\"", "conversations/", "audit/", "secrets/"] {
        assert!(!shell.contains(forbidden));
        assert!(!powershell.contains(forbidden));
    }
}

#[test]
fn runbook_release_evidence_and_gitea_platform_policy_are_complete() {
    let root = workspace();
    let runbook = fs::read_to_string(root.join("docs/grid-agent-operations.md")).unwrap();
    for required in [
        "Quick start",
        "Windows service operation",
        "Linux systemd",
        "Threat",
        "privacy",
        "Resource defaults",
        "Failure playbooks",
        "unsupported",
        "upgrade",
        "rollback",
        "orphan",
        "rotation",
        "firewall",
        "readiness",
    ] {
        assert!(
            runbook.to_lowercase().contains(&required.to_lowercase()),
            "runbook lacks {required}"
        );
    }
    let evidence = fs::read_to_string(root.join("docs/grid-agent-release-evidence.md")).unwrap();
    assert!(evidence.contains("28,658,000 bytes"));
    assert!(evidence.contains("192 unique Cargo"));
    assert!(evidence.contains("no CLR/Mono/.NET"));
    for workflow in ["ci.yml", "release.yml"] {
        let text = fs::read_to_string(root.join(".gitea/workflows").join(workflow)).unwrap();
        assert!(
            text.lines()
                .filter(|line| line.contains("runs-on:"))
                .all(|line| line.contains("ubuntu-latest"))
        );
    }
}
