# SPDX-License-Identifier: AGPL-3.0-or-later
"""Open-defect registry enforcement (report-recurring-failures.md Tier-3 #17).

``tests/open_defects.yaml`` registers every ``test_bug_*`` pin with its status.
The meta-class that blessed 11+ bugs was exactly this surface going unguarded:
pins weakened, made vacuous, or deleted silently. This suite forbids that.
"""
from __future__ import annotations

import ast
import os
import subprocess
import sys

import yaml

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TESTS_ROOT = os.path.join(PROJECT_ROOT, "tests")
REGISTRY_PATH = os.path.join(TESTS_ROOT, "open_defects.yaml")
VALID_STATUSES = {"open", "fixed"}


def _registry() -> dict:
    with open(REGISTRY_PATH) as handle:
        return yaml.safe_load(handle)


def _bug_pins():
    """Map test name -> (module path, function source) for every test_bug_*."""
    pins = {}
    for name in sorted(os.listdir(TESTS_ROOT)):
        if not name.endswith(".py"):
            continue
        path = os.path.join(TESTS_ROOT, name)
        with open(path) as handle:
            source = handle.read()
        tree = ast.parse(source)
        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef) and node.name.startswith("test_bug_"):
                pins[node.name] = (
                    os.path.join("tests", name),
                    ast.get_source_segment(source, node) or "",
                )
    return pins


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_bug_pin_is_registered_and_registered_pins_exist():
    registry = _registry()
    registered = {}
    for defect_id, entry in (registry.get("defects") or {}).items():
        assert entry.get("status") in VALID_STATUSES, defect_id
        for node_id in entry.get("tests") or []:
            name = node_id.rsplit("::", 1)[1]
            assert name.startswith("test_bug_"), node_id
            assert name not in registered, f"{name} registered twice"
            registered[name] = defect_id
    pins = _bug_pins()
    missing = sorted(set(pins) - set(registered))
    stale = sorted(set(registered) - set(pins))
    assert not missing, f"test_bug_* pins missing from open_defects.yaml: {missing}"
    assert not stale, f"open_defects.yaml pins that no longer exist: {stale}"


def test_every_registered_pin_collects():
    registry = _registry()
    collected = _collected_node_ids()
    assert collected, "pytest collected no test node ids"
    missing = {}
    for defect_id, entry in (registry.get("defects") or {}).items():
        gone = [
            node
            for node in entry.get("tests", [])
            # A registered function id covers its parametrised variants.
            if not any(item == node or item.startswith(node + "[") for item in collected)
        ]
        if gone:
            missing[defect_id] = gone
    assert not missing, f"registered pins no longer collect: {missing}"


def test_defect_pins_are_not_vacuous():
    """A pin with no assertion or raises-block is a weakened pin (the shape the
    meta-class exploited)."""
    vacuous = [
        name
        for name, (_path, source) in sorted(_bug_pins().items())
        if "assert " not in source and "pytest.raises" not in source
    ]
    assert not vacuous, f"vacuous test_bug_* pins: {vacuous}"


def test_status_floors_hold():
    registry = _registry()
    statuses = [
        entry.get("status") for entry in (registry.get("defects") or {}).values()
    ]
    assert statuses.count("fixed") >= registry.get("min_fixed", 0)
    assert statuses.count("open") >= registry.get("min_open", 0)
