import json
import subprocess
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def run_runtime_baseline(*args: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["python3", "ops/apply_gcp_runtime_baseline.py", *args],
        cwd=REPO_ROOT,
        text=True,
        capture_output=True,
        check=False,
    )


def test_gcp_runtime_baseline_dry_run_writes_planned_operations(tmp_path: Path) -> None:
    output = tmp_path / "runtime-baseline.json"
    completed = run_runtime_baseline("--admin-ssh-cidr", "198.51.100.10/32", "--output", str(output))

    assert completed.returncode == 0, completed.stderr
    payload = json.loads(output.read_text())
    assert payload["mode"] == "dry_run"
    assert payload["status"] == "planned"
    assert payload["failed_operation_count"] == 0
    operation_names = {operation["name"] for operation in payload["operations"]}
    assert "create_vm:teleo-prod-1" in operation_names
    assert "create_vm:teleo-staging-1" in operation_names
    assert "create_bucket:teleo-501523-prod-backups" in operation_names
    assert "create_cloudsql_instance:teleo-pgvector-standby" in operation_names
    assert "add_secret_version:gcp-teleo-pgvector-standby-postgres-password" in operation_names
    assert all(operation["exitcode"] is None for operation in payload["operations"])


def test_gcp_runtime_baseline_dry_run_does_not_record_raw_password(tmp_path: Path, monkeypatch) -> None:
    monkeypatch.setenv("TELEO_CLOUDSQL_POSTGRES_PASSWORD", "do-not-record-this")
    output = tmp_path / "runtime-baseline.json"
    completed = run_runtime_baseline("--admin-ssh-cidr", "198.51.100.10/32", "--output", str(output))

    assert completed.returncode == 0, completed.stderr
    text = output.read_text()
    assert "do-not-record-this" not in text
    assert "--root-password=$TELEO_CLOUDSQL_POSTGRES_PASSWORD" in text


def test_gcp_runtime_baseline_execute_requires_admin_ssh_cidr_without_shelling_out(tmp_path: Path) -> None:
    output = tmp_path / "runtime-baseline.json"
    completed = run_runtime_baseline("--execute", "--output", str(output))

    assert completed.returncode == 1
    payload = json.loads(output.read_text())
    assert payload["mode"] == "execute"
    assert payload["status"] == "failed"
    assert payload["operations"] == [
        {
            "action": "validate",
            "command": [],
            "exitcode": 1,
            "name": "validate_admin_ssh_cidr",
            "stderr_tail": "--admin-ssh-cidr is required in execute mode",
            "stdout_tail": "",
        }
    ]


def test_gcp_runtime_baseline_contract_is_part_of_readiness_checker() -> None:
    checker = (REPO_ROOT / "ops/check_gcp_infra_readiness.py").read_text()
    docs = (REPO_ROOT / "docs/gcp-infra-hardening-20260707.md").read_text()

    assert "check_gcp_runtime_baseline_contract" in checker
    assert "apply_gcp_runtime_baseline.py" in checker
    assert "Current-State Rule" in docs
    assert "apply_gcp_runtime_baseline.py" in docs
