"""Error formatting and escalation helpers for orchestration safeguards."""

from __future__ import annotations

from typing import Callable

import typer


# @invar:allow shell_result: Formatter returns escalation message string for CLI/operator display
# @shell_orchestration: Pure formatter intentionally co-located with orchestration error emission
def build_step_not_found_escalation(
    workflow_id: str,
    step_id: str,
    phase: str,
    reason: str,
    attempted_actions: list[str],
) -> str:
    """Build a deterministic escalation message for missing orchestration steps.

    >>> text = build_step_not_found_escalation(
    ...     workflow_id="wf-1",
    ...     step_id="core.missing",
    ...     phase="core",
    ...     reason="No fallback available",
    ...     attempted_actions=["Checked fallback registry"],
    ... )
    >>> "ESCALATION REQUIRED" in text
    True
    >>> "core.missing" in text
    True
    """
    lines = [
        "ESCALATION REQUIRED: orchestration step not found",
        f"Workflow: {workflow_id}",
        f"Phase: {phase}",
        f"Missing step: {step_id}",
        f"Reason: {reason}",
        "Actions attempted:",
    ]
    if attempted_actions:
        lines.extend(f"  - {action}" for action in attempted_actions)
    else:
        lines.append("  - none")
    return "\n".join(lines)


def emit_escalation(message: str, sink: Callable[[str], None] | None = None) -> None:
    """Emit an escalation message to sink (or stderr via typer by default).

    >>> captured: list[str] = []
    >>> emit_escalation("hello", captured.append)
    >>> captured
    ['hello']
    """
    if sink is not None:
        sink(message)
        return
    typer.secho(message, fg=typer.colors.RED)
