"""The no-ungoverned-secret gate (SPEC §7.5) — C3 as a permanent contract.

A live-but-undeclared secret (or deploy key) must make doctor exit 1. This is the
standing enforcement that growth *forces* registration.
"""

from __future__ import annotations

from mgf.secrets.doctor import Doctor
from mgf.secrets.forge import DeployKey
from mgf.secrets.registry import load
from tests._fakes import FakeForge, FakeWoodpecker

# A registry that declares exactly one org secret.
REGISTRY = """\
[declared_secret]
family = "mgf"
kind = "api-token"
purpose = "declared"
consumers = ["x"]
recovery = "re-mint"
state = "active"
policy = { allowed_repos = "*", blast_radius = "low" }
rotation = { class = "token", staged = true }
verify = { probe = "auth" }
surfaces = [ { type = "woodpecker-org-secret", events = ["push"] } ]

[fleet_key]
family = "mgf"
kind = "ssh-deploy-key"
purpose = "fleet deploy key"
consumers = ["clone"]
recovery = "re-add"
state = "active"
policy = { allowed_repos = "*", blast_radius = "read" }
rotation = { class = "static-key", staged = true }
verify = { probe = "forge-key-fingerprint" }
surfaces = [ { type = "forge-deploy-key", repos = "ALL_MANAGED", readonly = true, title = "declared-key" } ]
"""


def _reg(tmp_path):
    p = tmp_path / "SECRETS.toml"
    p.write_text(REGISTRY, encoding="utf-8")
    return load([p])


def test_live_undeclared_org_secret_exits_1(tmp_path) -> None:
    reg = _reg(tmp_path)
    wp = FakeWoodpecker(
        org_secrets={"declared_secret": {"push"}, "ungoverned_secret": {"push"}},
        repos=[],
    )
    report = Doctor(reg, fed_root=tmp_path, woodpecker=wp).run(["woodpecker"])
    assert report.exit_code() == 1
    assert any(
        f.check == "C3" and f.evidence.get("name") == "ungoverned_secret" for f in report.findings
    )


def test_fully_declared_fleet_is_clean(tmp_path) -> None:
    reg = _reg(tmp_path)
    wp = FakeWoodpecker(org_secrets={"declared_secret": {"push"}}, repos=[])
    report = Doctor(reg, fed_root=tmp_path, woodpecker=wp).run(["woodpecker"])
    assert report.exit_code() == 0
    assert not report.findings


def test_live_undeclared_deploy_key_exits_1(tmp_path) -> None:
    reg = _reg(tmp_path)
    wp = FakeWoodpecker(repos=[(1, "mgf-standard")])
    forge = FakeForge(
        {
            "mgf-standard": [
                DeployKey(title="declared-key", fingerprint="SHA256:a", read_only=True),
                DeployKey(title="rogue-key", fingerprint="SHA256:b", read_only=True),
            ]
        }
    )
    report = Doctor(reg, fed_root=tmp_path, woodpecker=wp, forge=forge).run(["forge"])
    assert report.exit_code() == 1
    assert any(f.check == "C3" and f.evidence.get("title") == "rogue-key" for f in report.findings)
