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

import pytest

from orchestrator import events
from orchestrator.store import CrashInjected, EventStore, IdempotencyConflict, ReplayError
from helpers import build_run_config


@pytest.fixture
def store(tmp_path):
    path = str(tmp_path / "events.db")
    s = EventStore(path)
    yield s
    s.close()


def _proposed(node_id="n1", idem="p1"):
    return events.make_event(
        "NODE_PROPOSED",
        {"node_id": node_id, "contract": {}, "cause": "ROOT"},
        idempotency_key=idem,
    )


def test_admit_persists_and_assigns_sequence(store):
    result = store.admit("r1", _proposed())
    assert result.seq == 1
    assert result.mutated is True
    assert store.state("r1").nodes["n1"].state == "PROPOSED"


def test_duplicate_event_is_idempotent(store):
    e1 = _proposed(idem="dup-1")
    first = store.admit("r1", e1)
    e2 = _proposed(idem="dup-1")  # identical payload and idempotency key
    second = store.admit("r1", e2)
    assert second.duplicate is True
    assert second.mutated is False
    history = store.history("r1")
    assert len(history) == 1, "a duplicate event must not append a second log row"


def test_conflicting_idempotency_key_is_rejected(store):
    store.admit("r1", _proposed(idem="k1"))
    conflicting = events.make_event(
        "NODE_PROPOSED",
        {"node_id": "n1", "contract": {"different": True}, "cause": "ROOT"},
        idempotency_key="k1",
    )
    with pytest.raises(IdempotencyConflict):
        store.admit("r1", conflicting)
    assert len(store.history("r1")) == 1


def test_duplicate_admission_does_not_duplicate_ledger_charge(store):
    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor

    def script(request):
        return {
            "self_reported_status": "COMPLETED",
            "artefacts": [{"type": "GIT_CANDIDATE", "content_hash": "abc123"}],
            "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
        }

    controller = Controller(store, ScriptedExecutor({"r1-root": script}))
    node_id = controller.submit_run(build_run_config("r1"))
    attempt_id = controller.plan_attempt("r1", node_id, 5)
    token = controller.dispatch_attempt("r1", attempt_id, node_id)
    response = controller.executor.dispatch(
        {"run_id": "r1", "attempt_id": attempt_id, "attempt_token": token, "node_id": node_id}
    )
    controller.admit_observation_and_result("r1", attempt_id, node_id, token, response)

    before = controller.get_costs("r1")["total_charged"]
    # Re-admitting the identical reconcile event (duplicate delivery) must not
    # re-charge the ledger. The payload matches the controller's emitted event
    # exactly, including the atomically computed reclamation.
    duplicate_event = events.make_event(
        "ATTEMPT_COST_RECONCILED",
        {"attempt_id": attempt_id, "actual": 5, "reclamation": 5.0 - 5},
        idempotency_key=f"r1:ATTEMPT_COST_RECONCILED:reconcile-{attempt_id}",
    )
    result = store.admit("r1", duplicate_event)
    assert result.duplicate is True
    after = controller.get_costs("r1")["total_charged"]
    assert before == after == 5


def test_replay_from_genesis_reproduces_state(store):
    from orchestrator.controller import Controller
    from orchestrator.executor import ScriptedExecutor

    def script(request):
        return {
            "self_reported_status": "COMPLETED",
            "artefacts": [{"type": "GIT_CANDIDATE", "content_hash": "abc123"}],
            "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
        }

    controller = Controller(store, ScriptedExecutor({"r1-root": script}))
    node_id = controller.submit_run(build_run_config("r1"))
    attempt_id = controller.plan_attempt("r1", node_id, 5)
    token = controller.dispatch_attempt("r1", attempt_id, node_id)
    response = controller.executor.dispatch(
        {"run_id": "r1", "attempt_id": attempt_id, "attempt_token": token, "node_id": node_id}
    )
    result_id = controller.admit_observation_and_result("r1", attempt_id, node_id, token, response)
    controller.validate_and_accept("r1", node_id, {"checks": ["BUILD"]}, result_id)

    live_state = store.state("r1")
    replayed_state = store.replay_fresh("r1")

    assert replayed_state.nodes[node_id].state == live_state.nodes[node_id].state == "ACCEPTED"
    assert replayed_state.outcome == live_state.outcome == "ACCEPTANCE_CLAIMED"
    assert replayed_state.graph_version == live_state.graph_version
    assert replayed_state.ledger.total_charged == live_state.ledger.total_charged == 5

    # Replay never dispatches work: the executor's response cache is untouched
    # by replay_fresh, proving no second dispatch occurred.
    assert len(controller.executor._responses) == 1


def test_full_log_replay_no_snapshots(store, tmp_path):
    # Restarting the store (a fresh EventStore over the same db file) must
    # reconstruct identical state purely from the persisted event log.
    store.admit("r1", _proposed())
    store.admit(
        "r1",
        events.make_event(
            "NODE_ADMITTED",
            {"node_id": "n1", "contract": {}, "authority": "controller"},
            idempotency_key="a1",
        ),
    )
    store.close()

    restarted = EventStore(store.db_path)
    try:
        assert restarted.state("r1").nodes["n1"].state == "BLOCKED"
    finally:
        restarted.close()


def test_replay_stops_on_unsupported_recorded_schema_version(store, tmp_path):
    # Simulate history recorded under a schema/policy version no longer
    # supported by the running reducer, bypassing admission's own guard (which
    # would already reject it) by inserting the row directly, the way it would
    # exist in a durable log from an earlier, now-unsupported release.
    store.admit("r1", _proposed())
    store._conn.execute(
        """
        INSERT INTO events (
            run_id, event_id, event_type, payload, idempotency_key, payload_hash,
            schema_version, policy_version, causation_id, correlation_id, source,
            event_time, ingestion_time, graph_version
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """,
        (
            "r1",
            "manually-inserted-event",
            "NODE_ADMITTED",
            '{"node_id": "n1", "contract": {}, "authority": "controller"}',
            "a1",
            "irrelevant-hash",
            99,  # unsupported schema version
            1,
            None,
            None,
            "controller",
            None,
            0.0,
            1,
        ),
    )

    with pytest.raises(ReplayError):
        store.replay_fresh("r1")

    # A fresh store restart replays from genesis too, and must stop the same way.
    store.close()
    with pytest.raises(ReplayError):
        EventStore(store.db_path)


def test_crash_after_commit_leaves_the_event_durable(tmp_path):
    # crash_after_commit simulates the boundary between "the transaction is
    # durable" and "the in-process cache is updated". A real crash there kills
    # the process; the only recovery path is reopening the store from the
    # durable log, which must already reflect the committed event.
    db_path = str(tmp_path / "events.db")
    store = EventStore(db_path)
    try:

        def boom(event):
            raise CrashInjected("simulated crash after commit")

        store.crash_after_commit = boom
        with pytest.raises(CrashInjected):
            store.admit("r1", _proposed())
    finally:
        store.close()

    restarted = EventStore(db_path)
    try:
        assert restarted.state("r1").nodes["n1"].state == "PROPOSED"
        assert len(restarted.history("r1")) == 1
    finally:
        restarted.close()
