import json
import subprocess
from pathlib import Path


def run_plan(*args: str) -> str:
    return subprocess.check_output(
        ["python3", "ops/plan_gcp_iam_split.py", *args],
        cwd=Path(__file__).resolve().parents[1],
        text=True,
    )


def test_gcp_iam_split_keeps_artifact_builder_narrow() -> None:
    plan = json.loads(run_plan())

    assert plan["kept_narrow"]["artifact_service_account"] == (
        "sa-artifact-builder@teleo-501523.iam.gserviceaccount.com"
    )
    assert plan["readiness_service_account"] == "sa-teleo-readiness@teleo-501523.iam.gserviceaccount.com"
    assert plan["restore_service_account"] == "sa-teleo-restore-drill@teleo-501523.iam.gserviceaccount.com"
    assert "roles/artifactregistry.writer" not in plan["readiness_project_roles"]
    assert "roles/cloudsql.editor" not in plan["readiness_project_roles"]
    assert "roles/compute.viewer" in plan["readiness_project_roles"]
    assert "roles/cloudsql.viewer" in plan["readiness_project_roles"]
    assert "roles/secretmanager.viewer" in plan["readiness_project_roles"]
    assert plan["restore_project_roles"] == ["roles/cloudsql.editor"]
    assert plan["restore_bucket_roles"] == ["roles/storage.objectAdmin"]


def test_gcp_iam_split_shell_plan_has_post_apply_checks() -> None:
    shell = run_plan("--format", "shell")

    assert "sa-teleo-readiness" in shell
    assert "sa-teleo-restore-drill" in shell
    assert "roles/iam.workloadIdentityUser" in shell
    assert "CLOUDSQL_INSTANCE_SA=$(gcloud sql instances describe" in shell
    assert '--member "serviceAccount:${CLOUDSQL_INSTANCE_SA}"' in shell
    assert "gh workflow run gcp-readiness.yml" in shell
