# SPDX-License-Identifier: AGPL-3.0-or-later
"""A2 verifier-mutation coverage meta-test.

``tests/verifier_registry.yaml`` must name every verifier that trusts an
authoritative object, and each verifier must map a content mutation and an
identity/version mutation that assert rejection. This test fails if a verifier
is added without coverage, if a mapped test stops collecting, or if the two
mutation kinds collapse to the same test.
"""
from __future__ import annotations

import os

import yaml

from collection import collected_node_ids

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGISTRY_PATH = os.path.join(PROJECT_ROOT, "tests", "verifier_registry.yaml")

REQUIRED_VERIFIERS = frozenset(
    {
        "import_verification",
        "manifest_binding",
        "acceptance_reducer_guard",
        "oracle_classifier",
        "model_output_admission",
        "spend_ledger_authorization",
        "freeze_normalisation",
        "delegated_scope_normalisation",
        "graded_tree_binding",
        "frozen_model_binding",
    }
)
MUTATION_KINDS = ("content", "identity")


def _load() -> dict:
    with open(REGISTRY_PATH) as handle:
        return yaml.safe_load(handle)["verifiers"]


def test_registry_covers_every_required_verifier():
    registered = set(_load())
    assert registered == REQUIRED_VERIFIERS, (
        f"verifier registry drift: missing={sorted(REQUIRED_VERIFIERS - registered)} "
        f"unexpected={sorted(registered - REQUIRED_VERIFIERS)}"
    )


def test_every_registered_verifier_has_two_resolvable_mutations():
    collected = collected_node_ids()
    assert collected, "pytest collected no node ids"
    problems = {}
    for name, entry in _load().items():
        assert entry.get("authoritative_input"), f"{name} has no authoritative input"
        mutations = entry.get("mutations") or {}
        if set(mutations) != set(MUTATION_KINDS):
            problems[name] = f"expected {MUTATION_KINDS}, got {sorted(mutations)}"
            continue
        missing = [
            node for kind, node in mutations.items() if node not in collected
        ]
        if missing:
            problems[name] = f"mapped tests no longer collect: {missing}"
    assert not problems, f"verifier mutation coverage gaps: {problems}"


def test_content_and_identity_mutations_are_distinct():
    same = [
        name
        for name, entry in _load().items()
        if entry["mutations"]["content"] == entry["mutations"]["identity"]
    ]
    assert not same, f"content and identity mutations collapse for: {same}"
