"""Double-confirm flow helpers for high-risk stop-zone actions (Phase D)."""

from __future__ import annotations

from typing import Callable

from iuve_connect_agents.shared.feature_flags import avatar_double_confirm_enabled

from .command_models import CommandEnvelope, ConfirmationCallback, ConfirmationResult, PolicyDecision

DoubleConfirmStepCallback = Callable[[CommandEnvelope, PolicyDecision, int], ConfirmationResult]


def requires_double_confirm(decision: PolicyDecision) -> bool:
    if not avatar_double_confirm_enabled():
        return False
    return str(decision.confirm_type or "").strip().lower() == "double_confirm"


def run_double_confirm(
    envelope: CommandEnvelope,
    decision: PolicyDecision,
    *,
    step_callback: DoubleConfirmStepCallback,
) -> ConfirmationResult:
    """Two-step owner approval: preview (step 1) then verification (step 2)."""
    if not requires_double_confirm(decision):
        return step_callback(envelope, decision, 1)

    first = step_callback(envelope, decision, 1)
    if first != "approve":
        return first
    second = step_callback(envelope, decision, 2)
    return second


def wrap_confirmation_callback(callback: ConfirmationCallback) -> ConfirmationCallback:
    """Wrap a single-step callback to honour double_confirm when enabled."""

    def _wrapped(envelope: CommandEnvelope, decision: PolicyDecision) -> ConfirmationResult:
        if not requires_double_confirm(decision):
            return callback(envelope, decision)

        def _step_cb(env: CommandEnvelope, dec: PolicyDecision, step: int) -> ConfirmationResult:
            enriched = PolicyDecision(
                allowed=dec.allowed,
                reason_code=dec.reason_code,
                error_message=dec.error_message,
                require_confirmation=dec.require_confirmation,
                capability_key=dec.capability_key,
                confirm_type=dec.confirm_type,
                stop_zone=dec.stop_zone,
            )
            if step == 2:
                payload = dict(env.payload)
                payload["double_confirm_step"] = 2
                env = CommandEnvelope(
                    command_id=env.command_id,
                    command_type=env.command_type,
                    payload=payload,
                    requested_at=env.requested_at,
                    expires_at=env.expires_at,
                )
            return callback(env, enriched)

        return run_double_confirm(envelope, decision, step_callback=_step_cb)

    return _wrapped
