# SPDX-License-Identifier: AGPL-3.0-or-later
"""Invariants over arbitrary ledger operation sequences (A3).

These are deliberately small and are proven falsifiable in
``tests/test_ledger_fuzzer.py`` by injecting a violating sequence.

- ``no_overcommitment``: active reservations plus active commitments on any
  budget and dimension never exceed that budget's authorised limit.
- ``charged_is_counted_once``: ``total_charged`` equals the sum of ACTUAL
  entries, and each attempt's charged amount matches its ACTUAL entry.
- ``settled_attempts_have_no_active_liability``: a settled attempt retains no
  active reservation or commitment.
- ``overruns_are_recorded``: an attempt settled above its commitment has the
  excess recorded as explicit overrun liability.
"""
from __future__ import annotations

from typing import Dict, List

from orchestrator.model import Ledger, TOLERANCE

ACTIVE_LIABILITY = ("RESERVATION", "COMMITMENT")


def no_overcommitment(ledger: Ledger) -> List[str]:
    violations: List[str] = []
    for budget_id, record in ledger.budgets.items():
        for dimension, limit in record.limits.items():
            active = sum(
                entry.amount
                for entry in ledger.entries.values()
                if entry.dimension == dimension
                and entry.kind in ACTIVE_LIABILITY
                and entry.active
                and budget_id in entry.ancestor_budget_path
            )
            if active > limit + TOLERANCE:
                violations.append(
                    f"budget {budget_id!r} dimension {dimension!r} has {active} active "
                    f"liability above its limit {limit}"
                )
    return violations


def charged_is_counted_once(ledger: Ledger) -> List[str]:
    violations: List[str] = []
    actual_total = 0.0
    actuals: Dict[str, float] = {}
    for entry in ledger.entries.values():
        if entry.kind == "ACTUAL":
            actual_total += entry.amount
            actuals[entry.attempt_id] = entry.amount
    if abs(actual_total - ledger.total_charged) > TOLERANCE:
        violations.append(
            f"total_charged {ledger.total_charged} != sum of ACTUAL entries {actual_total}"
        )
    for attempt_id, amount in ledger.charged.items():
        if attempt_id not in actuals or abs(actuals[attempt_id] - amount) > TOLERANCE:
            violations.append(
                f"attempt {attempt_id!r} charged {amount} but its ACTUAL entry is "
                f"{actuals.get(attempt_id)!r}"
            )
    return violations


def settled_attempts_have_no_active_liability(ledger: Ledger) -> List[str]:
    settled = set(ledger.charged)
    return [
        f"settled attempt {entry.attempt_id!r} still carries an active {entry.kind}"
        for entry in ledger.entries.values()
        if entry.attempt_id in settled and entry.kind in ACTIVE_LIABILITY and entry.active
    ]


def overruns_are_recorded(ledger: Ledger) -> List[str]:
    commitments: Dict[str, float] = {}
    for entry in ledger.entries.values():
        if entry.kind == "COMMITMENT":
            commitments[entry.attempt_id] = entry.amount
    violations: List[str] = []
    for attempt_id, actual in ledger.charged.items():
        commitment = commitments.get(attempt_id)
        if commitment is None:
            continue
        expected = max(0.0, actual - commitment)
        recorded = ledger.overruns.get(attempt_id, 0.0)
        if abs(recorded - expected) > TOLERANCE:
            violations.append(
                f"attempt {attempt_id!r} overrun {expected} is not the recorded "
                f"liability {recorded}"
            )
    return violations


LEDGER_INVARIANTS = (
    no_overcommitment,
    charged_is_counted_once,
    settled_attempts_have_no_active_liability,
    overruns_are_recorded,
)


def collect_ledger_violations(ledger: Ledger) -> Dict[str, List[str]]:
    fired: Dict[str, List[str]] = {}
    for invariant in LEDGER_INVARIANTS:
        violations = invariant(ledger)
        if violations:
            fired[invariant.__name__] = violations
    return fired


def assert_ledger_invariants(ledger: Ledger) -> None:
    fired = collect_ledger_violations(ledger)
    assert not fired, f"ledger invariant violations: {fired}"
