# SPDX-License-Identifier: AGPL-3.0-or-later
"""R10: retry eligibility is derived before validation changes the node state,
and validation identities are cycle-specific so a repaired node re-validates.
"""
from __future__ import annotations

import pytest

from helpers import build_run_config

from orchestrator import acceptance_checks
from orchestrator.controller import AcceptanceRefused, Controller
from orchestrator.executor import ScriptedExecutor
from orchestrator.model_adapter import ModelClient
from orchestrator.store import EventStore

RUN_ID = "RUN-R10"


def _harness(tmp_path):
    script = lambda request: {  # noqa: E731
        "self_reported_status": "COMPLETED",
        "observations": [
            {"type": "COMMAND_RESULT", "command_id": "BUILD", "exit_code": 0, "signal": None}
        ],
        "artefacts": [],
        "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
    }
    store = EventStore(str(tmp_path / "r10.db"))
    executor = ScriptedExecutor({f"{RUN_ID}-root": script})
    controller = Controller(store, executor)
    root = controller.submit_run(build_run_config(RUN_ID, budgets={"MODEL_COST": 10.0}))
    attempt = controller.execute_attempt(RUN_ID, root, 5.0)
    return store, controller, root, attempt


def _evidence(controller, node_id, passed, evidence_id):
    return controller.admit_evidence(
        RUN_ID,
        node_id,
        acceptance_checks.AcceptanceEvidence(
            check_class="VISIBLE",
            checks=(acceptance_checks.AcceptanceCheckResult(name="BUILD", passed=passed),),
            artefact_hashes={},
            versions={},
        ),
        evidence_id=evidence_id,
    )


def test_first_failed_validation_is_retry_eligible(tmp_path):
    """The retry-policy decision is computed while the node is still READY; the
    old ordering moved it to VALIDATING first, so every first failure was
    ineligible."""
    store, controller, root, attempt = _harness(tmp_path)
    try:
        bad = _evidence(controller, root, False, "ev-bad")
        with pytest.raises(AcceptanceRefused):
            controller.authorise_acceptance(
                RUN_ID, root, evidence_ids=[bad], result_id=f"{attempt}-result"
            )
        failed = [
            event
            for event in store.history(RUN_ID)
            if event.event_type == "VALIDATION_FAILED"
        ]
        assert failed
        assert failed[-1].payload["retry_eligible"] is True
        # Retryable means the guarded alternative returns the node to READY.
        assert store.state(RUN_ID).nodes[root].state == "READY"
    finally:
        store.close()


def test_repaired_node_revalidates_under_a_fresh_cycle_identity(tmp_path):
    """A failure then a repair re-validates: the second cycle's events are
    admitted instead of colliding with the failed cycle's identities."""
    store, controller, root, attempt = _harness(tmp_path)
    try:
        bad = _evidence(controller, root, False, "ev-bad")
        with pytest.raises(AcceptanceRefused):
            controller.authorise_acceptance(
                RUN_ID, root, evidence_ids=[bad], result_id=f"{attempt}-result"
            )
        good = _evidence(controller, root, True, "ev-good")
        controller.authorise_acceptance(
            RUN_ID, root, evidence_ids=[good], result_id=f"{attempt}-result"
        )
        state = store.state(RUN_ID)
        assert state.nodes[root].state == "ACCEPTED"
        starts = [
            event
            for event in store.history(RUN_ID)
            if event.event_type == "VALIDATION_STARTED"
        ]
        assert len(starts) == 2
        assert starts[0].idempotency_key != starts[1].idempotency_key
    finally:
        store.close()


def test_repeated_identical_failures_reach_a_recorded_terminal_outcome(tmp_path):
    """R10: two identical failures are driven through REPLAN_REQUIRED to a
    terminal INFEASIBLE outcome for the failing node, and a root failure makes
    the run outcome INFEASIBLE."""
    store, controller, root, attempt = _harness(tmp_path)
    try:
        for index in (1, 2):
            bad = _evidence(controller, root, False, f"ev-bad-{index}")
            with pytest.raises(AcceptanceRefused):
                controller.authorise_acceptance(
                    RUN_ID, root, evidence_ids=[bad], result_id=f"{attempt}-result"
                )
            controller.record_failure(
                RUN_ID,
                root,
                action_type="EXECUTE",
                diagnostic_category="VISIBLE_VALIDATION_FAILED",
                evidence_digest="sha256:identical",
            )
            controller.evaluate_repeated_failure(
                RUN_ID, root, replan_material_change=True
            )
        if store.state(RUN_ID).nodes[root].state == "REPLAN_REQUIRED":
            controller.evaluate_repeated_failure(
                RUN_ID, root, replan_material_change=False
            )
        state = store.state(RUN_ID)
        assert state.nodes[root].state == "INFEASIBLE"
        assert state.outcome == "INFEASIBLE"
        failures = [
            event
            for event in store.history(RUN_ID)
            if event.event_type == "VALIDATION_FAILED"
        ]
        assert len(failures) == 2
        replans = [
            event
            for event in store.history(RUN_ID)
            if event.event_type == "REPLAN_REQUESTED"
        ]
        assert replans
    finally:
        store.close()


def test_two_cycle_validation_failure_reaches_terminal_infeasible(tmp_path):
    """F1: with a fresh attempt per cycle (as the driver does), the second
    failure must drive the node to a recorded terminal INFEASIBLE and abort the
    trial with the driver's stopping signal, not raise UnknownTransition."""
    from helpers import build_run_config

    from orchestrator import experiment
    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor
    from orchestrator.store import EventStore

    run_id = "RUN-R10-DRIVER"

    def script(_request):
        return {
            "self_reported_status": "COMPLETED",
            "observations": [],  # admitted, but the visible checker fails
            "artefacts": [],
            "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
        }

    class _Integration:
        head = "base-commit"

    store = EventStore(str(tmp_path / "driver.db"))
    controller = Controller(store, ScriptedExecutor({f"{run_id}-root": script}))
    try:
        root = controller.submit_run(
            build_run_config(run_id, budgets={"MODEL_COST": 100.0})
        )
        limits = experiment.placeholder_limits()
        recorder = experiment._TrialRecorder("DIRECT", 1, run_id, limits, experiment.MODEL_PROFILE)
        with pytest.raises(experiment._TrialAborted):
            experiment._execute_leaf(
                controller, _Integration(), recorder, run_id, root, limits, 0,
                review=False,
            )
        state = store.state(run_id)
        assert state.nodes[root].state == "INFEASIBLE"
        assert state.outcome == "INFEASIBLE"
        assert len(state.attempts) == 2
    finally:
        store.close()


def test_evaluate_from_replan_required_marks_infeasible_not_illegal(tmp_path):
    """The defensive guard: calling the repeated-failure evaluation while the
    node is already REPLAN_REQUIRED records INFEASIBLE instead of raising an
    illegal REPLAN_REQUESTED transition, regardless of the material-change
    claim."""
    store, controller, root, attempt = _harness(tmp_path)
    try:
        for index in (1, 2):
            bad = _evidence(controller, root, False, f"ev-guard-{index}")
            with pytest.raises(AcceptanceRefused):
                controller.authorise_acceptance(
                    RUN_ID, root, evidence_ids=[bad], result_id=f"{attempt}-result"
                )
            controller.record_failure(
                RUN_ID,
                root,
                action_type="EXECUTE",
                diagnostic_category="VISIBLE_VALIDATION_FAILED",
                evidence_digest="sha256:identical",
            )
            controller.evaluate_repeated_failure(
                RUN_ID, root, replan_material_change=True
            )
        assert store.state(RUN_ID).nodes[root].state == "REPLAN_REQUIRED"
        # The node is already REPLAN_REQUIRED; a material-change claim must not
        # emit an illegal REPLAN_REQUESTED.
        assert (
            controller.evaluate_repeated_failure(
                RUN_ID, root, replan_material_change=True
            )
            == "INFEASIBLE"
        )
        assert store.state(RUN_ID).nodes[root].state == "INFEASIBLE"
    finally:
        store.close()


class FailingClient(ModelClient):
    """A client whose completion raises at the transport boundary."""

    def max_cost(self, request):
        return 1.0

    def max_tokens(self, request):
        return (10, 10)

    def complete(self, request):
        raise RuntimeError("provider transport error")


def test_provider_failure_terminates_the_trial_not_the_process(tmp_path):
    """A provider transport/protocol failure is a recorded execution failure
    that drives the trial to a terminal outcome, not an unhandled exception."""
    from helpers import build_run_config

    from orchestrator import experiment
    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor
    from orchestrator.model_adapter import ModelAdapter, ModelClient
    from orchestrator.store import EventStore

    run_id = "RUN-PROVIDER"

    class _Integration:
        head = "base-commit"

    store = EventStore(str(tmp_path / "provider.db"))
    adapter = ModelAdapter(FailingClient(), model_id="m", model_version="1")
    controller = Controller(store, ScriptedExecutor({}), model_executor=adapter)
    try:
        root = controller.submit_run(
            build_run_config(
                run_id,
                budgets={"MODEL_COST": 100.0},
                limits={
                    "root_model_input_tokens": 1000,
                    "root_model_output_tokens": 1000,
                    "model_calls": 4,
                },
            )
        )
        limits = experiment.placeholder_limits()
        recorder = experiment._TrialRecorder("DIRECT", 1, run_id, limits, experiment.MODEL_PROFILE)
        with pytest.raises(experiment._TrialAborted):
            experiment._execute_leaf(
                controller, _Integration(), recorder, run_id, root, limits, 0
            )
        state = store.state(run_id)
        assert state.nodes[root].state == "INFEASIBLE"
        assert state.outcome == "INFEASIBLE"
        assert [
            event
            for event in store.history(run_id)
            if event.event_type in ("DISPATCH_FAILED", "EXECUTOR_FAILED")
        ]
    finally:
        store.close()
