"""Tests for orchestration step-not-found safeguard behavior."""

from __future__ import annotations

from returns.result import Failure, Success

from lattice.shell.orchestration import run_orchestration_step


def test_run_orchestration_step_executes_registered_step() -> None:
    """Directly registered step executes without reconciliation."""
    handlers = {"core.validate": lambda: Success("ok")}

    result = run_orchestration_step(
        workflow_id="wf-1",
        step_id="core.validate",
        phase="core",
        step_handlers=handlers,
        fallback_registry={},
    )

    assert isinstance(result, Success)
    assert result.unwrap() == "ok"


def test_run_orchestration_step_reconciles_to_fallback_handler() -> None:
    """Missing step resolves to fallback and executes fallback handler."""
    handlers = {"core.default": lambda: Success("fallback-ran")}

    result = run_orchestration_step(
        workflow_id="wf-2",
        step_id="core.missing",
        phase="core",
        step_handlers=handlers,
        fallback_registry={"core.default": "core.default"},
    )

    assert isinstance(result, Success)
    assert result.unwrap() == "fallback-ran"


def test_run_orchestration_step_escalates_when_critical_step_missing() -> None:
    """Critical missing step fails fast and emits escalation."""
    escalations: list[str] = []

    result = run_orchestration_step(
        workflow_id="wf-3",
        step_id="core.critical",
        phase="core",
        step_handlers={},
        fallback_registry={"core.default": "core.default"},
        critical_steps={"core.critical"},
        escalation_handler=escalations.append,
    )

    assert isinstance(result, Failure)
    assert "Critical step 'core.critical' not found" in result.failure()
    assert len(escalations) == 1
    assert "ESCALATION REQUIRED" in escalations[0]


def test_run_orchestration_step_escalates_when_reconcile_target_missing() -> None:
    """Reconciled step ID still fails when no handler exists."""
    escalations: list[str] = []

    result = run_orchestration_step(
        workflow_id="wf-4",
        step_id="core.missing",
        phase="core",
        step_handlers={},
        fallback_registry={"core.default": "core.default"},
        escalation_handler=escalations.append,
    )

    assert isinstance(result, Failure)
    assert "no handler is registered" in result.failure()
    assert len(escalations) == 1
