# SPDX-License-Identifier: AGPL-3.0-or-later
"""The six acceptance demonstrations from docs/roadmap.md's first milestone.

Each test below is named after and documents one bullet under
"First milestone: schema-and-replay slice" in docs/roadmap.md. Together they
are this milestone's completion gate.
"""

from __future__ import annotations

import pytest

from orchestrator import events, schemas
from orchestrator.controller import Controller
from orchestrator.executor import ScriptedExecutor
from orchestrator.store import EventStore
from helpers import build_run_config

VALID_CONFIG = build_run_config("RUN-100")


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


@pytest.fixture
def controller(tmp_path):
    store = EventStore(str(tmp_path / "events.db"))
    node_key = f"{VALID_CONFIG['run_id']}-root"
    ctl = Controller(store, ScriptedExecutor({node_key: _completed_script}))
    yield ctl
    store.close()


def _run_to_acceptance(controller, config=VALID_CONFIG):
    run_id = config["run_id"]
    node_id = controller.submit_run(config)
    attempt_id = controller.plan_attempt(run_id, node_id, config["budgets"]["MODEL_COST"])
    token = controller.dispatch_attempt(run_id, attempt_id, node_id)
    response = controller.executor.dispatch(
        {"run_id": run_id, "attempt_id": attempt_id, "attempt_token": token, "node_id": node_id}
    )
    result_id = controller.admit_observation_and_result(run_id, attempt_id, node_id, token, response)
    controller.validate_and_accept(
        run_id, node_id, {"checks": ["BUILD"]}, result_id
    )
    return node_id, attempt_id


# 1. Valid run specifications are admitted; malformed ones are rejected.


def test_valid_run_specification_is_admitted(controller):
    node_id = controller.submit_run(VALID_CONFIG)
    status = controller.get_status(VALID_CONFIG["run_id"], node_id)
    assert status["node_state"] == "READY"


def test_malformed_run_specification_is_rejected(controller):
    malformed = dict(VALID_CONFIG)
    malformed.pop("run_id")
    with pytest.raises(schemas.SchemaValidationError):
        controller.submit_run(malformed)


# 2. One task reaches an evidence-bound acceptance claim.


def test_one_task_reaches_evidence_bound_acceptance_claim(controller):
    node_id, attempt_id = _run_to_acceptance(controller)
    run_id = VALID_CONFIG["run_id"]

    assert controller.get_status(run_id, node_id)["node_state"] == "ACCEPTED"
    assert controller.get_outcome(run_id) == "ACCEPTANCE_CLAIMED"

    evidence = controller.get_evidence(run_id, node_id)
    assert evidence == ["BUILD"], "the acceptance claim must be bound to recorded evidence"

    candidate = controller.get_candidate_reference(run_id)
    assert candidate is not None

    costs = controller.get_costs(run_id)
    assert costs["total_charged"] == 4.5

    # The harness-facing read outputs are themselves schema-conformant
    # documents, not just internal state.
    run_result = controller.get_run_result(run_id)
    schemas.validate("RunResult", run_result)
    assert run_result["outcome"] == "ACCEPTANCE_CLAIMED"
    assert run_result["candidate_artefact_id"] == candidate

    evidence_document = controller.get_evidence_retrieval(run_id, node_id)
    schemas.validate("EvidenceRetrieval", evidence_document)
    assert evidence_document["evidence"] == ["BUILD"]


# 3. Duplicate events do not duplicate state changes or charges.


def test_duplicate_events_do_not_duplicate_state_or_charges(controller):
    node_id, attempt_id = _run_to_acceptance(controller)
    run_id = VALID_CONFIG["run_id"]
    costs_before = controller.get_costs(run_id)["total_charged"]
    history_before = len(controller.get_event_history(run_id))

    # Re-submitting the identical run specification replays the same
    # idempotency keys for every step; nothing changes.
    controller.submit_run(VALID_CONFIG)

    duplicate_reconcile = events.make_event(
        "ATTEMPT_COST_RECONCILED",
        {"attempt_id": attempt_id, "actual": 4.5, "reclamation": 10.0 - 4.5},
        idempotency_key=f"{run_id}:ATTEMPT_COST_RECONCILED:reconcile-{attempt_id}",
    )
    result = controller.store.admit(run_id, duplicate_reconcile)
    assert result.duplicate is True

    assert controller.get_costs(run_id)["total_charged"] == costs_before
    assert len(controller.get_event_history(run_id)) == history_before
    assert controller.get_status(run_id, node_id)["node_state"] == "ACCEPTED"


# 4. Replay reproduces state, ledger, and terminal outcome without dispatching work.


def test_replay_reproduces_state_ledger_and_outcome_without_dispatch(controller):
    node_id, attempt_id = _run_to_acceptance(controller)
    run_id = VALID_CONFIG["run_id"]

    live = controller.store.state(run_id)
    dispatch_count_before = len(controller.executor._responses)

    replayed = controller.store.replay_fresh(run_id)

    assert replayed.nodes[node_id].state == live.nodes[node_id].state == "ACCEPTED"
    assert replayed.outcome == live.outcome == "ACCEPTANCE_CLAIMED"
    assert replayed.graph_version == live.graph_version
    assert replayed.ledger.total_charged == live.ledger.total_charged == 4.5
    assert replayed.attempts[attempt_id].state == live.attempts[attempt_id].state == "RESULT_PRODUCED"

    # No additional executor dispatch occurred as a side effect of replay.
    assert len(controller.executor._responses) == dispatch_count_before


# 5. Competing terminal conditions resolve by global event order.


def test_competing_terminal_conditions_resolve_by_global_event_order(controller):
    run_id = "RUN-101"
    config = dict(VALID_CONFIG, run_id=run_id)
    node_id = controller.submit_run(config)

    # One admitted event (BUDGET_EXHAUSTION_RECORDED) derives the run's first
    # terminal condition.
    controller._emit(run_id, "BUDGET_EXHAUSTION_RECORDED", {"node_id": node_id}, "budget-exhausted")
    assert controller.get_outcome(run_id) == "BUDGET_EXHAUSTED"

    # A second, competing terminal condition for the same root is admitted
    # afterwards (representing a different consequence that could have been
    # derived from the same evaluation). It is retained in the log but must
    # not change the already-admitted outcome.
    result = controller._emit(run_id, "NODE_MARKED_INFEASIBLE", {"node_id": node_id}, "infeasible-late")
    assert result.mutated is False
    assert controller.get_outcome(run_id) == "BUDGET_EXHAUSTED"

    # A late event arriving after the outcome is fixed also leaves it unchanged.
    late = controller._emit(run_id, "NODE_CANCELLED", {"node_id": node_id}, "cancel-late")
    assert late.mutated is False
    assert controller.get_outcome(run_id) == "BUDGET_EXHAUSTED"

    # Replay reproduces exactly the same admitted outcome.
    replayed = controller.store.replay_fresh(run_id)
    assert replayed.outcome == "BUDGET_EXHAUSTED"

    # All three events are retained in the event history for audit.
    history = controller.get_event_history(run_id)
    event_types = [e["event_type"] for e in history]
    assert event_types.count("BUDGET_EXHAUSTION_RECORDED") == 1
    assert event_types.count("NODE_MARKED_INFEASIBLE") == 1
    assert event_types.count("NODE_CANCELLED") == 1


# 6. Interruptions around persistence and dispatch boundaries show the
# recovery behaviour declared in docs/control-plane.md#crash-recovery.
# (Covered in depth by tests/test_crash_recovery.py; this test exercises the
# same behaviour through the harness-facing controller API end to end.)


def test_dispatch_boundary_interruption_recovers_deterministically(tmp_path):
    db_path = str(tmp_path / "events.db")
    run_id = "RUN-102"
    config = dict(VALID_CONFIG, run_id=run_id)
    node_key = f"{run_id}-root"

    store = EventStore(db_path)
    ctl = Controller(store, ScriptedExecutor({node_key: _completed_script}))
    node_id = ctl.submit_run(config)
    attempt_id = ctl.plan_attempt(run_id, node_id, 5)
    # Record dispatch durably, then "crash" before the executor is invoked.
    ctl.executor.issue_token(attempt_id)
    ctl._emit(run_id, "ACTION_DISPATCHED", {"attempt_id": attempt_id, "executor": "x"}, f"dispatch-{attempt_id}")
    store.close()

    restarted_store = EventStore(db_path)
    restarted_ctl = Controller(restarted_store, ScriptedExecutor({node_key: _completed_script}))
    recovered = restarted_ctl.recover(run_id)
    assert recovered == [attempt_id]
    assert restarted_store.state(run_id).attempts[attempt_id].state == "FAILED"
    assert restarted_ctl.get_costs(run_id)["total_charged"] == 5  # conservative settlement
    restarted_store.close()


# Cancellation is part of the one concrete harness workflow.


def test_cancel_before_result_moves_node_and_run_to_cancelled(controller):
    run_id = "RUN-103"
    config = dict(VALID_CONFIG, run_id=run_id)
    node_id = controller.submit_run(config)
    controller.plan_attempt(run_id, node_id, 5)

    # Cancel before dispatching to the executor.
    controller.cancel_run(run_id, node_id)
    assert controller.get_status(run_id, node_id)["node_state"] == "CANCELLED"
    assert controller.get_outcome(run_id) == "CANCELLED"
