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

from orchestrator.executor import (
    AttemptCancelled,
    AttemptTimedOut,
    ScriptedExecutor,
    UnknownAttemptToken,
)


def test_single_use_token_cannot_be_reissued():
    executor = ScriptedExecutor({})
    executor.issue_token("a1")
    with pytest.raises(ValueError):
        executor.issue_token("a1")


def test_dispatch_rejects_unknown_or_mismatched_token():
    executor = ScriptedExecutor({"n1": lambda r: {}})
    executor.issue_token("a1")
    with pytest.raises(UnknownAttemptToken):
        executor.dispatch({"attempt_id": "a1", "attempt_token": "wrong", "node_id": "n1"})


def test_duplicate_delivery_is_idempotent_and_does_not_rerun_script():
    calls = []

    def script(request):
        calls.append(request["attempt_id"])
        return {"self_reported_status": "COMPLETED", "cost_report": {"actual": 1}}

    executor = ScriptedExecutor({"n1": script})
    token = executor.issue_token("a1")
    request = {"attempt_id": "a1", "attempt_token": token, "node_id": "n1"}
    first = executor.dispatch(request)
    second = executor.dispatch(request)
    assert first == second
    assert calls == ["a1"], "the script must run exactly once despite duplicate delivery"


def test_cancelled_attempt_raises_on_dispatch():
    executor = ScriptedExecutor({"n1": lambda r: {}})
    token = executor.issue_token("a1")
    executor.cancel("a1")
    with pytest.raises(AttemptCancelled):
        executor.dispatch({"attempt_id": "a1", "attempt_token": token, "node_id": "n1"})


def test_timeout_signal_raises_attempt_timed_out():
    executor = ScriptedExecutor({"n1": lambda r: {"timeout": True}})
    token = executor.issue_token("a1")
    with pytest.raises(AttemptTimedOut):
        executor.dispatch({"attempt_id": "a1", "attempt_token": token, "node_id": "n1"})
