"""Tests for step reconciliation strategies and outcomes."""

from __future__ import annotations

from returns.result import Failure, Success

from lattice.shell.reconciliation import (
    ReconciliationStrategy,
    create_fallback_registry,
    reconcile_missing_step,
    select_reconciliation_strategy,
)


def test_create_fallback_registry_merges_defaults_and_overrides() -> None:
    """Registry includes phase defaults and step-specific overrides."""
    registry = create_fallback_registry(
        phase_defaults={"core": "core.default"},
        step_overrides={"core.validate": "core.backup"},
    )

    assert registry["core.default"] == "core.default"
    assert registry["core.validate"] == "core.backup"


def test_select_reconciliation_strategy_prefers_direct_fallback() -> None:
    """Direct step fallback takes precedence over phase default."""
    registry = {
        "core.validate": "core.backup",
        "core.default": "core.default",
    }

    strategy = select_reconciliation_strategy("core.validate", "core", registry)

    assert strategy == ReconciliationStrategy.FALLBACK


def test_reconcile_missing_step_returns_phase_default_when_available() -> None:
    """Missing step resolves to phase default fallback."""
    result = reconcile_missing_step(
        step_id="core.missing",
        phase="core",
        workflow_id="wf-20",
        fallback_registry={"core.default": "core.default"},
    )

    assert isinstance(result, Success)
    assert result.unwrap().resolved_step_id == "core.default"


def test_reconcile_missing_step_returns_failure_for_unrecoverable_step() -> None:
    """Reconciliation fails with explicit message when no fallback exists."""
    result = reconcile_missing_step(
        step_id="shell.missing",
        phase="shell",
        workflow_id="wf-21",
        fallback_registry={},
    )

    assert isinstance(result, Failure)
    assert "No fallback available" in result.failure()
