# SPDX-License-Identifier: AGPL-3.0-or-later
"""Guard-mutation matrix meta-test (report-recurring-failures.md Tier-1 #2).

``tests/guard_mutation_matrix.yaml`` registers every enforcement parameter
with its guard site and its sentinel rows. The meta-test makes the registry
authoritative:

- every run-limit key in ``schemas.RUN_LIMIT_KEYS`` must have a row, so a new
  frozen limit cannot ship without sentinel coverage;
- every registered site must resolve and every pinned test must collect;
- the parameter count holds a floor, so rows cannot be silently deleted.
"""
from __future__ import annotations

import importlib
import os
import subprocess
import sys

import yaml

from orchestrator import schemas

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TESTS_ROOT = os.path.join(PROJECT_ROOT, "tests")
MATRIX_PATH = os.path.join(TESTS_ROOT, "guard_mutation_matrix.yaml")


def _matrix() -> dict:
    with open(MATRIX_PATH) as handle:
        return yaml.safe_load(handle)


def _resolve_site(site: str):
    """Import the longest importable module prefix of a dotted site, then walk
    the remaining attribute path."""
    parts = site.split(".")
    target = None
    imported = 0
    for cut in range(len(parts), 0, -1):
        try:
            target = importlib.import_module(".".join(parts[:cut]))
            imported = cut
            break
        except ModuleNotFoundError:
            continue
    if target is None:
        raise ModuleNotFoundError(site)
    for part in parts[imported:]:
        target = getattr(target, part)
    return target


def _collected_node_ids() -> set:
    result = subprocess.run(
        [sys.executable, "-m", "pytest", "--collect-only", "-q", "-p", "no:cacheprovider"],
        cwd=PROJECT_ROOT,
        capture_output=True,
        text=True,
        check=False,
    )
    assert result.returncode == 0, (
        f"pytest --collect-only failed:\n{result.stdout}\n{result.stderr}"
    )
    return {
        line.strip()
        for line in result.stdout.splitlines()
        if line.startswith("tests/") and "::" in line
    }


def test_every_run_limit_key_has_a_matrix_row():
    matrix = _matrix()
    registered = {entry["name"] for entry in matrix.get("parameters") or []}
    missing = [
        key
        for key in schemas.RUN_LIMIT_KEYS
        if f"run-limit-{key}" not in registered
    ]
    assert not missing, (
        "frozen run limits without a guard-mutation row (a new enforcement "
        f"parameter must land with its sentinel matrix): {missing}"
    )


def test_matrix_sites_resolve_and_tests_collect():
    matrix = _matrix()
    collected = _collected_node_ids()
    assert collected, "pytest collected no test node ids"
    unresolved = []
    uncollected = {}
    for entry in matrix.get("parameters") or []:
        try:
            _resolve_site(entry["site"])
        except Exception as error:  # noqa: BLE001 - reported as a finding
            unresolved.append(f"{entry['name']}: {type(error).__name__}: {error}")
        gone = [
            node
            for node in entry.get("tests", [])
            if not any(item == node or item.startswith(node + "[") for item in collected)
        ]
        if gone:
            uncollected[entry["name"]] = gone
    assert not unresolved, f"matrix sites no longer resolve: {unresolved}"
    assert not uncollected, f"matrix tests no longer collect: {uncollected}"


def test_parameter_floor_holds():
    matrix = _matrix()
    count = len(matrix.get("parameters") or [])
    assert count >= matrix.get("min_parameters", 0), (
        f"only {count} guard parameters are registered; floor is "
        f"{matrix.get('min_parameters')}"
    )
