"""ALL_MANAGED is invocation-independent (SPEC-P4 §7a).

The coverage sweep must resolve the SAME union no matter which surfaces were
selected — or emit ``unverifiable`` if the activated source can't be reached. A cron
must never under-report because of how it was invoked.
"""

from __future__ import annotations

import json

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

FLEET = """\
[fleet_key]
family = "mgf"
kind = "ssh-deploy-key"
purpose = "fleet clone 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 = "ci-clone" } ]
"""


def _seed(tmp_path):
    (tmp_path / "mgf-standard").mkdir(parents=True)
    (tmp_path / "sooth-standard").mkdir(parents=True)
    (tmp_path / "mgf-standard" / "MGF_LIBRARIES.json").write_text(
        json.dumps({"libraries": [{"repo": "mgf-alembic"}]}), encoding="utf-8"
    )
    (tmp_path / "sooth-standard" / "SOOTH_LIBRARIES.json").write_text(
        json.dumps({"repos": [{"name": "soothfast"}]}), encoding="utf-8"
    )
    (tmp_path / "SECRETS.toml").write_text(FLEET, encoding="utf-8")
    return load([tmp_path / "SECRETS.toml"])


def test_all_managed_same_union_forge_only_vs_woodpecker_plus_forge(tmp_path) -> None:
    reg = _seed(tmp_path)
    key = DeployKey(title="ci-clone", fingerprint="SHA256:a", read_only=True)
    repos = [(1, "mgf-alembic"), (2, "activated-only")]
    keys = {r: [key] for r in ("mgf-alembic", "soothfast", "activated-only")}

    def run(surfaces):
        wp = FakeWoodpecker(repos=repos)
        return Doctor(reg, fed_root=tmp_path, woodpecker=wp, forge=FakeForge(keys)).run(surfaces)

    forge_only = run(["forge"])
    both = run(["woodpecker", "forge"])
    # The activated-only repo is in the union in BOTH invocations (7a).
    assert forge_only.managed is not None and both.managed is not None
    assert forge_only.managed.repos == both.managed.repos
    assert "activated-only" in forge_only.managed.repos
    assert forge_only.managed.activated_reachable is True


def test_forge_without_woodpecker_client_degrades_to_unverifiable(tmp_path) -> None:
    """No woodpecker client at all -> the activated source is UNREACHABLE, so the union
    is a lower bound and ALL_MANAGED is unverifiable — never a silent shrink to the
    committed libraries alone."""
    reg = _seed(tmp_path)
    key = DeployKey(title="ci-clone", fingerprint="SHA256:a", read_only=True)
    forge = FakeForge({"mgf-alembic": [key], "soothfast": [key]})
    report = Doctor(reg, fed_root=tmp_path, woodpecker=None, forge=forge).run(["forge"])
    assert report.exit_code() == 1
    assert report.managed is not None and report.managed.activated_reachable is False
    assert any(
        u.check == "ALL_MANAGED" and u.target == "woodpecker-activated" for u in report.unverifiable
    )
    js = report.to_json()
    assert js["managed"]["activated_reachable"] is False


def test_build_context_builds_woodpecker_client_for_forge_surface(tmp_path, monkeypatch) -> None:
    """The 7a wiring: requesting forge builds the woodpecker client too (best-effort),
    so ALL_MANAGED can include the activated set even on a forge-only invocation."""
    monkeypatch.setenv("WOODPECKER_TOKEN", "wp-token-fixture")
    monkeypatch.setenv("CODEBERG_TOKEN", "cb-token-fixture")
    ctx = build_context({"forge"}, root=tmp_path)
    assert ctx.woodpecker is not None  # forge-implied woodpecker client
    assert ctx.forge is not None
