# SPDX-License-Identifier: AGPL-3.0-or-later
"""orchestrator.tables (the runtime resolver) and scripts/tables.py (the
documentation generator/verifier) both load docs/tables/*.yaml independently.
The tests here prove they agree, first on the structural facts that matter to
both, then at the resolution level: for every (state, event, is_root)
combination of every committed machine, both resolvers must return the same
target or raise the same class of resolution error — including the entity-level
``select.root`` wildcard predicate, which only the resolvers evaluate.
"""

from __future__ import annotations

import pytest
import tables as scripts_tables  # scripts/tables.py, added to sys.path by conftest.py

from orchestrator import tables as runtime_tables

MACHINE_FILES = list(scripts_tables.MACHINES)

# Error-class equivalence between the two resolvers.
ERROR_CLASSES = (
    (scripts_tables.UnknownTransition, runtime_tables.UnknownTransition),
    (scripts_tables.AmbiguousTransition, runtime_tables.AmbiguousTransition),
    (scripts_tables.GuardRequired, runtime_tables.UnresolvedGuard),
)


def _outcome(resolver, *args, **kwargs):
    try:
        return ("target", resolver(*args, **kwargs))
    except Exception as error:
        for doc_side, runtime_side in ERROR_CLASSES:
            if isinstance(error, doc_side):
                return ("error", runtime_side)
        raise AssertionError(f"unexpected resolution error {error!r}") from error


def test_loaders_agree_on_states_and_terminal_sets():
    for filename in MACHINE_FILES:
        script_data = scripts_tables.load_yaml(filename)
        runtime_table = runtime_tables.load(filename)

        script_states = set(scripts_tables.state_names(script_data))
        assert script_states == set(runtime_table.states), filename

        assert set(script_data["terminal"]) == set(runtime_table.terminal), filename


def test_loaders_agree_on_transition_rows():
    for filename in MACHINE_FILES:
        script_data = scripts_tables.load_yaml(filename)
        runtime_table = runtime_tables.load(filename)

        script_rows = {
            (t["from"], t["event"], t["to"]) for t in script_data["transitions"]
        }
        runtime_rows = set()
        for row in runtime_table._explicit.values():
            runtime_rows.update((t.source, t.event, t.target) for t in row)
        runtime_rows.update(
            (t.source, t.event, t.target) for t in runtime_table._wildcard
        )
        assert script_rows == runtime_rows, filename


def test_loaders_agree_the_committed_tables_pass_scripts_verification():
    # scripts/tables.py's own structural checks (reachability, ambiguity) are
    # the authority for the committed documents; this just pins that the
    # runtime resolver is being exercised against tables that already pass.
    for filename in MACHINE_FILES:
        data = scripts_tables.load_yaml(filename)
        assert scripts_tables.find_unreachable_states(data) == [], filename
        assert scripts_tables.check_transition_ambiguity(filename, data) == [], filename


def test_resolvers_agree_for_every_state_event_and_root_flag():
    """Resolution-level cross-check across the full (state, event, is_root)
    space, including the select.root wildcards (any_non_terminal_non_root for
    NODE_SUPERSEDED and any_non_terminal_root for ROOT_REPLACED)."""
    checked = 0
    for filename in MACHINE_FILES:
        script_data = scripts_tables.load_yaml(filename)
        runtime_table = runtime_tables.load(filename)
        states = [None] + list(runtime_table.states)
        for state in states:
            for event in sorted(runtime_table.events):
                for is_root in (False, True):
                    doc_outcome = _outcome(
                        scripts_tables.resolve_transition,
                        script_data,
                        state,
                        event,
                        is_root=is_root,
                    )
                    try:
                        runtime_outcome = (
                            "target",
                            runtime_table.resolve(state, event, is_root=is_root).target,
                        )
                    except (
                        runtime_tables.UnknownTransition,
                        runtime_tables.AmbiguousTransition,
                        runtime_tables.UnresolvedGuard,
                    ) as error:
                        runtime_outcome = ("error", type(error))
                    assert doc_outcome == runtime_outcome, (
                        f"{filename}: ({state!r}, {event!r}, is_root={is_root}) resolves "
                        f"differently: doc-side {doc_outcome}, runtime {runtime_outcome}"
                    )
                    checked += 1
    # The committed tables exercise the select.root predicates: both resolvers
    # must agree that NODE_SUPERSEDED is root-excluding and ROOT_REPLACED is
    # root-only, from the same states.
    node_data = scripts_tables.load_yaml("node-lifecycle.yaml")
    for state in ("PROPOSED", "BLOCKED", "READY", "VALIDATING", "REPLAN_REQUIRED", "CONFLICTED"):
        assert scripts_tables.resolve_transition(
            node_data, state, "NODE_SUPERSEDED", is_root=False
        ) == "SUPERSEDED"
        with pytest.raises(scripts_tables.UnknownTransition):
            scripts_tables.resolve_transition(node_data, state, "NODE_SUPERSEDED", is_root=True)
        assert scripts_tables.resolve_transition(
            node_data, state, "ROOT_REPLACED", is_root=True
        ) == "SUPERSEDED"
        with pytest.raises(scripts_tables.UnknownTransition):
            scripts_tables.resolve_transition(node_data, state, "ROOT_REPLACED", is_root=False)
    assert checked > 0
