import json
import subprocess
from pathlib import Path

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


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


def test_gcp_iam_apply_dry_run_writes_planned_operations(tmp_path: Path) -> None:
    output = tmp_path / "iam-apply.json"
    completed = run_apply("--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
    assert payload["plan"]["readiness_service_account"] == "sa-teleo-readiness@teleo-501523.iam.gserviceaccount.com"
    assert payload["plan"]["restore_service_account"] == "sa-teleo-restore-drill@teleo-501523.iam.gserviceaccount.com"
    assert any(operation["name"].startswith("readiness_project_role:") for operation in payload["operations"])
    assert any(operation["name"].startswith("restore_bucket_role:") for operation in payload["operations"])
    assert any(operation["name"] == "describe_cloudsql_instance_service_account" for operation in payload["operations"])


def test_gcp_iam_apply_dry_run_does_not_shell_out_to_gcloud(tmp_path: Path) -> None:
    output = tmp_path / "iam-apply.json"
    completed = run_apply("--output", str(output))

    assert completed.returncode == 0, completed.stderr
    payload = json.loads(output.read_text())
    assert all(operation["exitcode"] is None for operation in payload["operations"])
    assert all(operation["stdout_tail"] == "" for operation in payload["operations"])
    assert all(operation["stderr_tail"] == "" for operation in payload["operations"])
