# SPDX-License-Identifier: AGPL-3.0-or-later
"""Applicability-guard table driven by the generated transition tables.

For every machine, every (state, event) pair is enumerated from the machine
definition. A pair declared by an explicit row or a matching wildcard must
resolve without raising :class:`UnknownTransition`; every other pair must be
rejected as unknown. This is the "an event not declared from this state is
retained or rejected" guard, and because the enumeration is generated, the
guard set cannot silently shrink: the per-machine declared-pair counts are
pinned, so deleting a transition or a wildcard fails this test.
"""
from __future__ import annotations

import pytest
import yaml

from orchestrator import tables
from orchestrator.paths import TABLES_DIR

LOADERS = {
    "node-lifecycle.yaml": tables.node_table,
    "attempt-lifecycle.yaml": tables.attempt_table,
    "artefact-lifecycle.yaml": tables.artefact_table,
    "accounting-lifecycle.yaml": tables.accounting_table,
    "result-freshness.yaml": tables.freshness_table,
    "model-output-lifecycle.yaml": tables.model_output_table,
    "approval-lifecycle.yaml": tables.approval_table,
    "credential-lifecycle.yaml": tables.credential_table,
}

# Pinned declared (state, event, is_root) pair counts. A transition or wildcard
# removal lowers the count and fails the test; an addition requires the new
# count to be recorded deliberately.
DECLARED_PAIRS = {
    "node-lifecycle.yaml": 120,
    "attempt-lifecycle.yaml": 50,
    "artefact-lifecycle.yaml": 16,
    "accounting-lifecycle.yaml": 12,
    "result-freshness.yaml": 28,
    "model-output-lifecycle.yaml": 6,
    "approval-lifecycle.yaml": 14,
    "credential-lifecycle.yaml": 4,
}


def _load(filename: str) -> dict:
    with open(TABLES_DIR / filename) as handle:
        return yaml.safe_load(handle)


def _is_declared(table: tables.TransitionTable, data: dict, state, event: str, is_root: bool) -> bool:
    for raw in data["transitions"]:
        if (
            raw["event"] == event
            and raw["from"] == state
            and raw["from"] not in table.wildcards
        ):
            return True
    for raw in data["transitions"]:
        if raw["event"] != event or raw["from"] not in table.wildcards:
            continue
        select = table.wildcards[raw["from"]].get("select") or {}
        if select.get("terminal") is False and state in table.terminal:
            continue
        if "root" in select and select["root"] != is_root:
            continue
        return True
    return False


def test_every_machine_table_file_has_a_runtime_loader():
    machine_files = set()
    for path in sorted(TABLES_DIR.glob("*.yaml")):
        data = yaml.safe_load(path.read_text())
        if isinstance(data, dict) and "machine" in data and "transitions" in data:
            machine_files.add(path.name)
    assert machine_files == set(LOADERS), (
        "machine table files and runtime loaders have drifted: "
        f"missing loaders={sorted(machine_files - set(LOADERS))} "
        f"stale loaders={sorted(set(LOADERS) - machine_files)}"
    )


@pytest.mark.parametrize("filename", sorted(LOADERS))
def test_undeclared_transitions_are_rejected(filename):
    table = LOADERS[filename]()
    data = _load(filename)
    declared = 0
    for state in (None, *table.states):
        for event in sorted(table.events):
            for is_root in (False, True):
                if _is_declared(table, data, state, event, is_root):
                    declared += 1
                    try:
                        table.resolve(state, event, is_root=is_root)
                    except tables.UnknownTransition as error:
                        pytest.fail(
                            f"{filename}: declared pair ({state!r}, {event!r}, is_root={is_root}) "
                            f"was rejected as unknown: {error}"
                        )
                    except (tables.AmbiguousTransition, tables.UnresolvedGuard):
                        pass
                else:
                    with pytest.raises(tables.UnknownTransition):
                        table.resolve(state, event, is_root=is_root)
    assert declared == DECLARED_PAIRS[filename], (
        f"{filename}: {declared} declared pairs, expected {DECLARED_PAIRS[filename]}; "
        "a guard was added or removed"
    )


@pytest.mark.parametrize("filename", sorted(LOADERS))
def test_events_outside_the_machine_are_rejected_from_every_state(filename):
    table = LOADERS[filename]()
    for state in (None, *table.states):
        with pytest.raises(tables.UnknownTransition):
            table.resolve(state, "NOT_AN_EVENT")


def test_guarded_alternatives_require_a_guard_context():
    checked = 0
    for table in (loader() for loader in LOADERS.values()):
        for state, event in sorted(table.guarded_alternatives):
            checked += 1
            with pytest.raises(tables.UnresolvedGuard):
                table.resolve(state, event)
    assert checked >= 1, "no guarded alternatives are declared"


def test_guarded_alternatives_resolve_with_a_guard():
    for table in (loader() for loader in LOADERS.values()):
        for state, event in sorted(table.guarded_alternatives):
            captured = {}

            def guard(rows):
                captured["rows"] = rows
                return rows[0]

            chosen = table.resolve(state, event, guard=guard)
            assert chosen in captured["rows"]
