# SPDX-License-Identifier: AGPL-3.0-or-later
"""Class B completion: coercion, epsilon, and exotic-type edges.

Every ledger and event-payload numeric boundary is pinned at its documented
edge (±1 ulp around the tolerance), exotic types are refused cleanly at both
ledgers, and event-payload numbers are refused as reducer errors instead of
being silently coerced (report-recurring-failures.md Tier-1 #3, class B).
"""
from __future__ import annotations

import math

import pytest

from helpers import build_run_config
from orchestrator import reducer
from orchestrator.controller import Controller
from orchestrator.executor import ScriptedExecutor
from orchestrator.model import BudgetRecord, Ledger, LedgerStateError, OvercommitmentError
from orchestrator.spend import SpendLedgerError
from orchestrator.store import EventStore

EXOTIC_AMOUNTS = [
    True,          # bool passes int comparisons: must be refused
    "5",
    None,
    float("nan"),
    float("inf"),
    float("-inf"),
    [1],
    {"amount": 1.0},
]


def _run_ledger():
    ledger = Ledger()
    ledger.register_budget(BudgetRecord("src", "n1", {"MODEL_COST": 10.0}))
    return ledger


def _funded_attempt(ledger, *, actual=None):
    """A reserved, committed attempt ready to settle; returns its attempt id."""
    ledger.reserve("e1", "src", 5.0, "MODEL_COST", "a1", "n1")
    ledger.commit_reservation("a1", 5.0, "MODEL_COST")
    return "a1"


# --------------------------------------------------------------------------
# Exotic amounts are refused cleanly at both ledgers (SPEND F10 class)
# --------------------------------------------------------------------------


@pytest.mark.parametrize("amount", EXOTIC_AMOUNTS)
def test_run_ledger_refuses_exotic_amounts(amount):
    ledger = _run_ledger()
    with pytest.raises(LedgerStateError):
        ledger.reserve("e1", "src", amount, "MODEL_COST", "a1", "n1")


@pytest.mark.parametrize("amount", EXOTIC_AMOUNTS)
def test_run_ledger_refuses_exotic_settlements(amount):
    ledger = _run_ledger()
    attempt_id = _funded_attempt(ledger)
    with pytest.raises(LedgerStateError):
        ledger.settle(attempt_id, amount, 0.0)
    # The refusal left the accounting untouched: nothing was laundered.
    entry = next(
        entry for entry in ledger.entries.values() if entry.kind == "COMMITMENT"
    )
    assert entry.active


@pytest.mark.parametrize("amount", EXOTIC_AMOUNTS)
def test_experiment_ledger_refuses_exotic_amounts(tmp_path, amount):
    from orchestrator import spend as spend_module

    ledger = spend_module.open_spend_ledger(
        str(tmp_path),
        spend_module.ExperimentAuthorization(
            owner="fuzz", limit=100.0, authorized_at="2026-01-01T00:00:00Z",
            method="test",
        ),
    )
    try:
        with pytest.raises(SpendLedgerError):
            ledger.reserve("EXP-DIRECT-1001", amount)
        with pytest.raises(SpendLedgerError):
            ledger.settle("EXP-DIRECT-1001", amount)
    finally:
        import os

        os.remove(os.path.join(str(tmp_path), "experiment-spend.json"))


# --------------------------------------------------------------------------
# Tolerance boundaries are pinned at ±1 ulp
# --------------------------------------------------------------------------


def test_settle_tolerance_boundary_is_inclusive_then_overrun():
    """The overrun gate compares the float subtraction ``actual - commitment``
    against the tolerance, so the pin sits safely inside (1e-10) and outside
    (2e-9) the tolerance rather than at its representational edge."""
    ledger = _run_ledger()
    attempt_id = _funded_attempt(ledger)
    ledger.settle(attempt_id, 5.0 + 1e-10, 0.0)
    assert ledger.total_overrun == 0.0
    ledger2 = _run_ledger()
    attempt2 = _funded_attempt(ledger2)
    ledger2.settle(attempt2, 5.0 + 2e-9, 0.0)
    assert ledger2.total_overrun > 0.0


def test_commitment_tolerance_boundary_is_inclusive_then_refused():
    ledger = _run_ledger()
    ledger.reserve("e1", "src", 5.0 + 1e-9, "MODEL_COST", "a1", "n1")
    # At exactly the tolerance the commitment is admitted.
    ledger.commit_reservation("a1", 5.0 + 1e-9, "MODEL_COST")
    ledger2 = _run_ledger()
    ledger2.reserve("e1", "src", 5.0 + 1e-9, "MODEL_COST", "a1", "n1")
    beyond = (5.0 + 1e-9) + 2e-9
    with pytest.raises(OvercommitmentError):
        ledger2.commit_reservation("a1", beyond, "MODEL_COST")


def test_transfer_tolerance_boundary_is_inclusive_then_refused():
    ledger = _run_ledger()
    ledger.register_budget(BudgetRecord("dst", "n2", {"MODEL_COST": 0.0}))
    edge = 10.0 + 1e-9
    ledger.transfer("src", "dst", {"MODEL_COST": edge})
    ledger2 = _run_ledger()
    ledger2.register_budget(BudgetRecord("dst", "n2", {"MODEL_COST": 0.0}))
    beyond = edge + math.ulp(edge)
    with pytest.raises(OvercommitmentError):
        ledger2.transfer("src", "dst", {"MODEL_COST": beyond})


# --------------------------------------------------------------------------
# Event-payload numbers are validated, never silently coerced (class B)
# --------------------------------------------------------------------------


def _reconcile_ready_attempt(tmp_path):
    """A run whose attempt accounting sits at PROVISIONALLY_SETTLED, ready to
    receive a (crafted) reconciliation."""
    store = EventStore(str(tmp_path / "events.db"))
    controller = Controller(store, ScriptedExecutor({}))
    root = controller.submit_run(build_run_config("FUZZ", budgets={"MODEL_COST": 50.0}))
    attempt_id = controller.plan_attempt("FUZZ", root, 5.0, action_type="EXECUTE")
    controller._emit(
        "FUZZ",
        "ACTION_DISPATCHED",
        {"attempt_id": attempt_id, "executor": "scripted-in-process"},
        f"dispatch-{attempt_id}",
    )
    controller._emit(
        "FUZZ",
        "ATTEMPT_EXECUTION_ENDED_UNRECONCILED",
        {"attempt_id": attempt_id},
        f"end-unreconciled-{attempt_id}",
    )
    return store, controller, attempt_id


@pytest.mark.parametrize("amount", EXOTIC_AMOUNTS)
def test_crafted_reconciliation_amounts_are_reducer_errors(tmp_path, amount):
    """A crafted or replayed reconciliation carrying a coerced number (a bool,
    a string, NaN, ...) is a reducer error and leaves the accounting exactly
    where it was (class B: event-payload numeric fuzz)."""
    store, controller, attempt_id = _reconcile_ready_attempt(tmp_path)
    try:
        before = store.state("FUZZ").attempts[attempt_id].accounting_state
        with pytest.raises(reducer.ReducerError):
            controller._emit(
                "FUZZ",
                "ATTEMPT_COST_RECONCILED",
                {"attempt_id": attempt_id, "actual": amount, "reclamation": 0.0},
                f"reconcile-fuzz-{amount!r}",
            )
        after = store.state("FUZZ").attempts[attempt_id].accounting_state
        assert after == before, "a refused payload must not change accounting"
    finally:
        store.close()


@pytest.mark.parametrize("amount", [True, "5", None, float("nan"), float("inf"), -1])
def test_controller_response_actual_is_never_coerced(tmp_path, amount):
    """The controller refuses an executor-reported actual that is not a finite
    non-negative number, before it can affect any ledger (R02)."""
    store = EventStore(str(tmp_path / "events.db"))
    controller = Controller(
        store,
        ScriptedExecutor({
            "FUZZ-root": lambda request: {
                "self_reported_status": "COMPLETED",
                "observations": [{"type": "COMMAND_RESULT", "exit_code": 0}],
                "artefacts": [],
                "cost_report": {"committed": 5, "actual": amount, "units": "COST_UNITS"},
            }
        }),
    )
    try:
        root = controller.submit_run(build_run_config("FUZZ", budgets={"MODEL_COST": 50.0}))
        from orchestrator import executor_protocol

        with pytest.raises(executor_protocol.ProtocolViolation):
            controller.execute_attempt("FUZZ", root, 5.0)
        state = store.state("FUZZ")
        attempt = state.attempts[next(iter(state.attempts))]
        assert attempt.state == "FAILED", (
            "the machine-legal refusal is RESULT_REJECTED, which fails the attempt"
        )
        assert attempt.accounting_state == "FINALLY_SETTLED"
    finally:
        store.close()
