# SPDX-License-Identifier: AGPL-3.0-or-later
"""Seeded state-machine fuzzer over legal controller operations.

The fuzzer drives the real controller with a fixed scripted executor, choosing
operations from a seeded RNG. Every step asserts the invariant library on the
reduced state, so an operation that leaves inconsistent liability, dangling
references, or clipped overspend fails with a reproducible seed.

Rejected operations (a domain refusal such as a terminal run, an exhausted
budget, or an unmet precondition) are expected and do not fail the walk; the
invariants are still asserted afterwards, because a refused operation must not
leave the state half-mutated.
"""
from __future__ import annotations

import random

import pytest

from orchestrator.controller import Controller, WorkflowError
from orchestrator.executor import ScriptedExecutor
from orchestrator.model import LedgerStateError, OvercommitmentError
from orchestrator import tables
from orchestrator.reducer import ReducerError
from orchestrator.store import EventStore

from helpers import build_run_config
from invariants import assert_invariants

SEEDS = (0, 1, 2, 3, 4, 5, 6, 7)
STEPS_PER_WALK = 24

EXPECTED_REFUSALS = (
    WorkflowError,
    ReducerError,
    LedgerStateError,
    OvercommitmentError,
    # The machine's own refusals surface from the store boundary unchanged
    # (an unknown/ambiguous/guard-required transition is a legal refusal —
    # e.g. a second acceptance authorisation reaches the freshness machine
    # and is refused there since the idempotency-key fix stopped silently
    # deduplicating it).
    tables.UnknownTransition,
    tables.AmbiguousTransition,
    tables.UnresolvedGuard,
)


def _script(_request):
    return {
        "self_reported_status": "COMPLETED",
        "artefacts": [{"type": "GIT_CANDIDATE", "content_hash": "sha256:fuzz"}],
        "observations": [{"type": "COMMAND_RESULT", "command_id": "BUILD", "exit_code": 0}],
        "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
    }


def _step(rng: random.Random, controller: Controller, run_id: str, root: str, step: int) -> None:
    state = controller.store.state(run_id)
    produced = [
        attempt.attempt_id
        for attempt in state.attempts.values()
        if attempt.node_id == root and attempt.state == "RESULT_PRODUCED"
    ]
    actions = [
        lambda: controller.plan_attempt(run_id, root, rng.choice([1.0, 2.0, 5.0, 50.0])),
        lambda: controller.execute_attempt(run_id, root, rng.choice([1.0, 2.0, 5.0, 50.0])),
    ]
    if step >= 4:
        actions.append(lambda: controller.cancel_run(run_id, root))
    if produced:
        attempt_id = rng.choice(produced)
        actions.append(
            lambda: controller.validate_and_accept(
                run_id, root, {"checks": ["BUILD"]}, f"{attempt_id}-result"
            )
        )
    rng.choice(actions)()


def _walk(seed: int, tmp_path) -> int:
    run_id = f"FUZZ-{seed}"
    store = EventStore(str(tmp_path / f"{run_id}.db"))
    controller = Controller(store, ScriptedExecutor({f"{run_id}-root": _script}))
    try:
        root = controller.submit_run(build_run_config(run_id))
        rng = random.Random(seed)
        for step in range(STEPS_PER_WALK):
            try:
                _step(rng, controller, run_id, root, step)
            except EXPECTED_REFUSALS:
                pass
            assert_invariants(store.state(run_id))
        return len(store.history(run_id))
    finally:
        store.close()


@pytest.mark.parametrize("seed", SEEDS)
def test_seeded_state_machine_walk_preserves_invariants(seed, tmp_path):
    # Guard against a vacuous walk: the run must admit a non-trivial number of
    # events, not just collect refusals.
    assert _walk(seed, tmp_path) >= 4


def test_walks_are_not_vacuous(tmp_path):
    admitted = sum(_walk(seed, tmp_path) for seed in SEEDS)
    assert admitted >= 80, f"the fuzzer admitted only {admitted} events across {len(SEEDS)} seeds"

