# SPDX-License-Identifier: AGPL-3.0-or-later
"""Invariants over the reduced ``RunState``.

These predicates are deliberately small and independent. Each one targets a
recurring defect class rather than a single bug:

- referential integrity of relations, attempts, timers, and artefacts;
- liability (active reservations and commitments) tracking live attempts;
- budgets and ledger ancestor paths staying consistent;
- overspend being recorded rather than clipped.

Every predicate is mutation-proven in ``tests/test_invariants.py``: the state is
tampered directly and the predicate must fire. A predicate that cannot be shown
to fire is treated as a defect, because a weak invariant creates false
confidence.
"""
from __future__ import annotations

from typing import Callable, Dict, List

from orchestrator import tables
from orchestrator.model import LedgerStateError, RunState, TOLERANCE

ACTIVE_LIABILITY_KINDS = ("RESERVATION", "COMMITMENT")


def invariant_attempts_reference_admitted_nodes(state: RunState) -> List[str]:
    return [
        f"attempt {attempt_id!r} references unknown node {attempt.node_id!r}"
        for attempt_id, attempt in state.attempts.items()
        if attempt.node_id not in state.nodes
    ]


def invariant_relations_reference_admitted_nodes(state: RunState) -> List[str]:
    violations: List[str] = []
    for relation_id, relation in state.relations.items():
        for endpoint in (relation.from_node_id, relation.to_node_id):
            if endpoint not in state.nodes:
                violations.append(
                    f"relation {relation_id!r} references unknown node {endpoint!r}"
                )
    return violations


def invariant_timers_reference_known_attempts(state: RunState) -> List[str]:
    return [
        f"timer {timer_id!r} references unknown attempt {timer.attempt_id!r}"
        for timer_id, timer in state.timers.items()
        if timer.attempt_id not in state.attempts
    ]


def invariant_active_liability_has_an_attempt(state: RunState) -> List[str]:
    violations: List[str] = []
    for entry_id, entry in state.ledger.entries.items():
        if entry.kind in ACTIVE_LIABILITY_KINDS and entry.active:
            if not entry.attempt_id or entry.attempt_id not in state.attempts:
                violations.append(
                    f"active {entry.kind} {entry_id!r} has no live attempt "
                    f"({entry.attempt_id!r})"
                )
    return violations


def invariant_settled_attempts_carry_no_active_liability(state: RunState) -> List[str]:
    accounting_table = tables.accounting_table()
    violations: List[str] = []
    for entry_id, entry in state.ledger.entries.items():
        if entry.kind not in ACTIVE_LIABILITY_KINDS or not entry.active:
            continue
        attempt = state.attempts.get(entry.attempt_id)
        if attempt is not None and accounting_table.is_terminal(attempt.accounting_state):
            violations.append(
                f"settled attempt {attempt.attempt_id!r} still carries an active "
                f"{entry.kind} {entry_id!r}"
            )
    return violations


def invariant_ledger_entries_reference_registered_budgets(state: RunState) -> List[str]:
    violations: List[str] = []
    for entry_id, entry in state.ledger.entries.items():
        if entry.budget_id not in state.ledger.budgets:
            violations.append(
                f"ledger entry {entry_id!r} references unknown budget {entry.budget_id!r}"
            )
            continue
        try:
            expected = state.ledger.ancestor_path(entry.budget_id)
        except LedgerStateError as error:
            violations.append(f"ledger entry {entry_id!r} has an unresolved budget chain: {error}")
            continue
        if tuple(entry.ancestor_budget_path) != expected:
            violations.append(
                f"ledger entry {entry_id!r} ancestor path {tuple(entry.ancestor_budget_path)} "
                f"does not match the budget chain {expected}"
            )
    return violations


def invariant_budget_parent_chains_are_resolved(state: RunState) -> List[str]:
    violations: List[str] = []
    for budget_id, budget in state.ledger.budgets.items():
        seen = {budget_id}
        current = budget.parent_budget_id
        while current is not None:
            if current in seen:
                violations.append(f"budget {budget_id!r} has a cyclic parent chain")
                break
            if current not in state.ledger.budgets:
                violations.append(
                    f"budget {budget_id!r} references unknown parent {current!r}"
                )
                break
            seen.add(current)
            current = state.ledger.budgets[current].parent_budget_id
    return violations


def invariant_root_is_present_when_nodes_exist(state: RunState) -> List[str]:
    if not state.nodes:
        return []
    if state.root_node_id is None:
        return ["nodes exist but no root node is recorded"]
    if state.root_node_id not in state.nodes:
        return [f"root node {state.root_node_id!r} is not an admitted node"]
    return []


def invariant_overruns_are_recorded_not_clipped(state: RunState) -> List[str]:
    violations: List[str] = []
    for attempt_id, attempt in state.attempts.items():
        if attempt.actual_cost is None or attempt.commitment is None:
            continue
        actual = float(attempt.actual_cost)
        commitment = float(attempt.commitment)
        charged = state.ledger.charged.get(attempt_id)
        if charged is None or abs(charged - actual) > TOLERANCE:
            violations.append(
                f"attempt {attempt_id!r} reported actual {actual} but the ledger "
                f"charged {charged}"
            )
        overrun = max(0.0, actual - commitment)
        recorded = state.ledger.overruns.get(attempt_id, 0.0)
        if abs(recorded - overrun) > TOLERANCE:
            violations.append(
                f"attempt {attempt_id!r} overrun {overrun} is not the recorded "
                f"liability {recorded}"
            )
    return violations


INVARIANTS: tuple[Callable[[RunState], List[str]], ...] = (
    invariant_attempts_reference_admitted_nodes,
    invariant_relations_reference_admitted_nodes,
    invariant_timers_reference_known_attempts,
    invariant_active_liability_has_an_attempt,
    invariant_settled_attempts_carry_no_active_liability,
    invariant_ledger_entries_reference_registered_budgets,
    invariant_budget_parent_chains_are_resolved,
    invariant_root_is_present_when_nodes_exist,
    invariant_overruns_are_recorded_not_clipped,
)


def orphan_child_budget_violations(state: RunState) -> List[str]:
    """A child budget (one with a parent budget) must have its child node.

    Registration happens as part of decomposition admission, before the child
    node events commit. Recovery must complete the continuation rather than
    leave an allocation with no node behind it.

    A terminal run is exempt: recovery deliberately does not resurrect the child
    for a run that already reached an outcome (R14 review F3), so an allocation
    the terminal run can no longer act on is not a violation."""
    if state.outcome is not None:
        return []
    return [
        f"child budget {budget_id!r} for node {budget.node_id!r} has no node"
        for budget_id, budget in state.ledger.budgets.items()
        if budget.parent_budget_id is not None and budget.node_id not in state.nodes
    ]


def collect_violations(state: RunState) -> Dict[str, List[str]]:
    """Return ``{invariant name: violations}`` for every predicate that fires."""
    fired: Dict[str, List[str]] = {}
    for invariant in INVARIANTS:
        violations = invariant(state)
        if violations:
            fired[invariant.__name__] = violations
    return fired


def assert_invariants(state: RunState) -> None:
    fired = collect_violations(state)
    assert not fired, f"invariant violations: {fired}"


def assert_recovery_invariants(state: RunState) -> None:
    """Invariants that must hold once recovery has run to quiescence."""
    assert_invariants(state)
    orphans = orphan_child_budget_violations(state)
    assert not orphans, f"recovery left orphan child budgets: {orphans}"
