# SPDX-License-Identifier: AGPL-3.0-or-later
import pytest

from orchestrator import events, reducer, tables
from orchestrator.model import RunState


def _event(event_type, payload, idem="k1"):
    return events.make_event(event_type, payload, idempotency_key=idem)


def test_unknown_event_type_is_rejected_at_admission():
    with pytest.raises(events.UnknownEventType):
        events.validate_event(_event("NOT_A_REAL_EVENT", {}))


def test_unknown_enum_value_is_rejected_at_admission():
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "NOT_A_CAUSE"})
        )


def test_missing_required_field_is_rejected():
    with pytest.raises(events.MissingPayloadField):
        events.validate_event(_event("NODE_PROPOSED", {"node_id": "n1", "contract": {}}))


def test_validation_failed_requires_retry_eligible_recorded():
    with pytest.raises(events.MissingPayloadField):
        events.validate_event(
            _event("VALIDATION_FAILED", {"node_id": "n1", "evidence": {}})
        )


def test_mismatched_source_authority_is_rejected():
    # READINESS_ESTABLISHED is catalogued as sourced by the Scheduler; a
    # controller-sourced event of that type must be rejected at admission
    # (docs/control-plane.md's "Event and proposal requirements": every event
    # records "source" and "source authority").
    event = events.make_event(
        "READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"}, source="controller"
    )
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(event)

    correctly_sourced = events.make_event(
        "READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"}, source="scheduler"
    )
    events.validate_event(correctly_sourced)  # must not raise


def test_unsupported_policy_version_is_rejected():
    event = events.make_event(
        "NODE_PROPOSED",
        {"node_id": "n1", "contract": {}, "cause": "ROOT"},
        policy_version=99,
    )
    with pytest.raises(events.UnsupportedPolicyVersion):
        events.validate_event(event)


def test_node_lifecycle_happy_path():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    assert state.nodes["n1"].state == "PROPOSED"
    assert state.root_node_id == "n1"

    state, _ = reducer.reduce(
        state,
        _event("NODE_ADMITTED", {"node_id": "n1", "contract": {}, "authority": "controller"}),
    )
    assert state.nodes["n1"].state == "BLOCKED"

    state, _ = reducer.reduce(
        state, _event("READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"})
    )
    assert state.nodes["n1"].state == "READY"


def test_explicit_row_takes_precedence_over_wildcard():
    # NODE_REJECTED has both an explicit PROPOSED row and a wildcard
    # any_non_terminal row; both apply to PROPOSED, but resolve() must use the
    # single explicit row rather than raising ambiguity.
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    state, effects = reducer.reduce(state, _event("NODE_REJECTED", {"node_id": "n1", "reason": "bad"}))
    assert state.nodes["n1"].state == "REJECTED"
    assert state.outcome == "REJECTED"


def test_guarded_alternative_validation_failed_retry_permitted():
    state = _ready_node()
    state, _ = reducer.reduce(state, _event("VALIDATION_STARTED", {"node_id": "n1"}))
    state, _ = reducer.reduce(
        state,
        _event(
            "VALIDATION_FAILED",
            {"node_id": "n1", "evidence": {}, "retry_eligible": True},
        ),
    )
    assert state.nodes["n1"].state == "READY"


def test_guarded_alternative_validation_failed_retry_prohibited():
    state = _ready_node()
    state, _ = reducer.reduce(state, _event("VALIDATION_STARTED", {"node_id": "n1"}))
    state, _ = reducer.reduce(
        state,
        _event(
            "VALIDATION_FAILED",
            {"node_id": "n1", "evidence": {}, "retry_eligible": False},
        ),
    )
    assert state.nodes["n1"].state == "REPLAN_REQUIRED"


def _ready_node():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    state, _ = reducer.reduce(
        state, _event("NODE_ADMITTED", {"node_id": "n1", "contract": {}, "authority": "controller"})
    )
    state, _ = reducer.reduce(
        state, _event("READINESS_ESTABLISHED", {"node_id": "n1", "action": "EXECUTE"})
    )
    return state


def test_late_event_after_terminal_root_is_a_no_op():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    state, _ = reducer.reduce(state, _event("NODE_REJECTED", {"node_id": "n1", "reason": "bad"}))
    assert state.outcome == "REJECTED"
    graph_version_before = state.graph_version

    # A late NODE_CANCELLED targeting the already-terminal root must not move
    # the outcome or the node state (docs/roadmap.md milestone item 5).
    state, effects = reducer.reduce(state, _event("NODE_CANCELLED", {"node_id": "n1"}))
    assert state.nodes["n1"].state == "REJECTED"
    assert state.outcome == "REJECTED"
    assert state.graph_version == graph_version_before
    assert any(e.kind == "late_event_retained" for e in effects)


def test_run_outcome_precedence_first_admitted_terminal_wins():
    # Simulate "one event deriving several conditions at once" by admitting
    # two competing terminal events for the same root in a fixed order: only
    # the first actually mutates the outcome; the second is a retained no-op,
    # regardless of which condition it represents.
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state, _event("NODE_PROPOSED", {"node_id": "n1", "contract": {}, "cause": "ROOT"})
    )
    state, _ = reducer.reduce(
        state, _event("NODE_ADMITTED", {"node_id": "n1", "contract": {}, "authority": "controller"})
    )
    state, _ = reducer.reduce(
        state, _event("BUDGET_EXHAUSTION_RECORDED", {"node_id": "n1"}, idem="e1")
    )
    assert state.outcome == "BUDGET_EXHAUSTED"

    state, effects = reducer.reduce(state, _event("NODE_MARKED_INFEASIBLE", {"node_id": "n1"}, idem="e2"))
    assert state.outcome == "BUDGET_EXHAUSTED"  # unchanged: the first terminal transition wins
    assert any(e.kind == "late_event_retained" for e in effects)


def test_result_admitted_requires_finally_settled_accounting():
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state,
        _event(
            "NODE_PROPOSED",
            {"node_id": "n1", "contract": {"budgets": {"MODEL_COST": 100}}, "cause": "ROOT"},
        ),
    )
    state, _ = reducer.reduce(
        state, _event("ATTEMPT_PLANNED", {"attempt_id": "a1", "node_id": "n1", "cause": "INITIAL"})
    )
    state, _ = reducer.reduce(state, _event("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 1}))
    state, _ = reducer.reduce(state, _event("ACTION_DISPATCHED", {"attempt_id": "a1", "executor": "x"}))
    state, _ = reducer.reduce(state, _event("DISPATCH_ACKNOWLEDGED", {"attempt_id": "a1", "token": "t"}))
    state, _ = reducer.reduce(
        state, _event("EXECUTOR_OBSERVATION_ADMITTED", {"attempt_id": "a1", "observation": {}})
    )
    with pytest.raises(reducer.ReducerError):
        reducer.reduce(state, _event("RESULT_ADMITTED", {"attempt_id": "a1", "result": {}}))


def test_duplicate_transition_ambiguity_detected_by_table():
    node_table = tables.node_table()
    with pytest.raises(tables.UnresolvedGuard):
        node_table.resolve("VALIDATING", "VALIDATION_FAILED")
