# SPDX-License-Identifier: AGPL-3.0-or-later
"""Mutation-proven invariant tests.

Every predicate in ``tests/invariants.py`` is exercised two ways:

1. it must hold on a healthy reduced state, and
2. it must fire when the state is tampered directly.

The corpus walk then asserts the same invariants after every event of the
frozen conformance corpus, so a reducer regression that produces an
inconsistent intermediate state is caught, not only a final-state drift.
"""
from __future__ import annotations

from typing import Callable, Dict

from orchestrator import conformance, reducer
from orchestrator.model import (
    ArtefactRecord,
    AttemptRecord,
    BudgetRecord,
    NodeRecord,
    RelationRecord,
    RunState,
    TimerRecord,
)

from invariants import INVARIANTS, assert_invariants, collect_violations


def build_healthy_state() -> RunState:
    state = RunState(run_id="RUN-INV", root_node_id="root")
    state.nodes["root"] = NodeRecord("root", "READY", {}, "ROOT", is_root=True)
    state.nodes["child"] = NodeRecord("child", "READY", {}, "DECOMPOSITION")
    state.relations["rel-1"] = RelationRecord(
        "rel-1", "CHILD_OF", "child", "root", {"mandatory": True}
    )
    state.ledger.register_budget(BudgetRecord("root-budget", "root", {"MODEL_COST": 10.0}))
    state.ledger.register_budget(
        BudgetRecord("child-budget", "child", {"MODEL_COST": 4.0}, parent_budget_id="root-budget")
    )
    state.attempts["a1"] = AttemptRecord("a1", "child", "RUNNING", accounting_state="OPEN")
    state.ledger.reserve("e1", "child-budget", 4.0, "MODEL_COST", "a1", "child")
    state.ledger.commit_reservation("a1", 4.0, "MODEL_COST")
    state.timers["t1"] = TimerRecord("t1", "a1", 123.0)
    state.artefacts["art-1"] = ArtefactRecord("art-1", "a1", "PRODUCED", "GIT_CANDIDATE", "sha256:x")
    return state


def build_settled_overrun_state() -> RunState:
    state = build_healthy_state()
    state.attempts["a1"].commitment = 4.0
    state.ledger.settle("a1", 6.0, 0.0)
    state.attempts["a1"].actual_cost = 6.0
    state.attempts["a1"].state = "RESULT_PRODUCED"
    state.attempts["a1"].accounting_state = "FINALLY_SETTLED"
    return state


def _tamper_unknown_attempt_node() -> RunState:
    state = build_healthy_state()
    state.attempts["orphan"] = AttemptRecord("orphan", "ghost", "RUNNING")
    return state


def _tamper_unknown_relation_endpoint() -> RunState:
    state = build_healthy_state()
    state.relations["bad"] = RelationRecord("bad", "CHILD_OF", "ghost", "root")
    return state


def _tamper_unknown_timer_attempt() -> RunState:
    state = build_healthy_state()
    state.timers["bad"] = TimerRecord("bad", "ghost", 1.0)
    return state


def _tamper_liability_without_attempt() -> RunState:
    state = build_healthy_state()
    del state.attempts["a1"]
    return state


def _tamper_settled_attempt_with_open_liability() -> RunState:
    state = build_healthy_state()
    state.attempts["a1"].state = "RESULT_PRODUCED"
    state.attempts["a1"].accounting_state = "FINALLY_SETTLED"
    return state


def _tamper_unknown_budget() -> RunState:
    state = build_healthy_state()
    state.ledger.entries["e1-commitment"].budget_id = "ghost"
    return state


def _tamper_unknown_budget_parent() -> RunState:
    state = build_healthy_state()
    state.ledger.budgets["child-budget"].parent_budget_id = "ghost"
    return state


def _tamper_missing_root() -> RunState:
    state = build_healthy_state()
    state.root_node_id = "ghost"
    return state


def _tamper_clipped_overrun() -> RunState:
    state = build_settled_overrun_state()
    state.ledger.overruns.pop("a1")
    return state


TAMPERINGS: Dict[str, Callable[[], RunState]] = {
    "invariant_attempts_reference_admitted_nodes": _tamper_unknown_attempt_node,
    "invariant_relations_reference_admitted_nodes": _tamper_unknown_relation_endpoint,
    "invariant_timers_reference_known_attempts": _tamper_unknown_timer_attempt,
    "invariant_active_liability_has_an_attempt": _tamper_liability_without_attempt,
    "invariant_settled_attempts_carry_no_active_liability": _tamper_settled_attempt_with_open_liability,
    "invariant_ledger_entries_reference_registered_budgets": _tamper_unknown_budget,
    "invariant_budget_parent_chains_are_resolved": _tamper_unknown_budget_parent,
    "invariant_root_is_present_when_nodes_exist": _tamper_missing_root,
    "invariant_overruns_are_recorded_not_clipped": _tamper_clipped_overrun,
}


def test_healthy_state_satisfies_every_invariant():
    assert collect_violations(build_healthy_state()) == {}


def test_settled_overrun_state_satisfies_every_invariant():
    assert collect_violations(build_settled_overrun_state()) == {}


def test_every_invariant_is_registered_with_a_tamper():
    assert {invariant.__name__ for invariant in INVARIANTS} == set(TAMPERINGS)


def test_every_invariant_fires_when_tampered():
    for invariant in INVARIANTS:
        tampered = TAMPERINGS[invariant.__name__]()
        violations = invariant(tampered)
        assert violations, f"{invariant.__name__} did not fire on its tampering"
        # The failure must be visible through the aggregate entry point too.
        assert invariant.__name__ in collect_violations(tampered)


def test_corpus_replay_preserves_invariants(tmp_path):
    runs = conformance.build_corpus(str(tmp_path))
    checked = 0
    for run in runs:
        state = RunState(run_id=run.run_id)
        for event in run.store.history(run.run_id):
            state, _ = reducer.reduce(state, event)
            assert_invariants(state)
            checked += 1
        run.store.close()
    assert checked > 0, "the corpus produced no events to replay"
