"""Stop-zone policy table — command_type → StopZone (Phase D)."""

from __future__ import annotations

from .confirm_type import ConfirmType
from .stop_zone import StopZone, confirm_type_for_stop_zone

# Table-driven mapping: command_type → stop-zone category.
COMMAND_STOP_ZONES: dict[str, StopZone] = {
    # 1. Publish
    "email_send": StopZone.PUBLISH,
    "social_post_publish": StopZone.PUBLISH,
    "browser_click_publish": StopZone.PUBLISH,
    "comment_submit": StopZone.PUBLISH,
    "message_send": StopZone.PUBLISH,
    # 2. Money
    "payment_execute": StopZone.MONEY,
    "subscription_confirm": StopZone.MONEY,
    # 3. Destroy
    "folder_wipe": StopZone.DESTROY,
    "db_drop": StopZone.DESTROY,
    "package_remove": StopZone.DESTROY,
    # 4. Secrets
    "token_export": StopZone.SECRETS,
    "2fa_change": StopZone.SECRETS,
    # 5. System
    "apply_update": StopZone.SYSTEM,
    "service_restart": StopZone.SYSTEM,
    "firewall_change": StopZone.SYSTEM,
    "install_unknown_software": StopZone.SYSTEM,
    # 6. Legal / reputation
    "mass_mail_send": StopZone.LEGAL,
    "public_accusation_post": StopZone.LEGAL,
}

# Draft / in-scope handlers — no stop-zone (confirm via session when granted).
DRAFT_COMMAND_TYPES = frozenset(
    {
        "social_post_draft",
        "email_compose",
    }
)

STOP_ZONE_RISK_TIER: dict[StopZone, str] = {
    StopZone.PUBLISH: "high",
    StopZone.MONEY: "critical",
    StopZone.DESTROY: "high",
    StopZone.SECRETS: "critical",
    StopZone.SYSTEM: "high",
    StopZone.LEGAL: "high",
}


def _coerce_stop_zone(value: StopZone | str | None) -> StopZone | None:
    if value is None:
        return None
    if isinstance(value, StopZone):
        return value
    raw = str(value).strip().lower()
    if not raw:
        return None
    try:
        return StopZone(raw)
    except ValueError:
        return None


def resolve_stop_zone(
    command_type: str,
    *,
    stop_zone_tag: StopZone | str | None = None,
) -> StopZone | None:
    """Resolve stop-zone from explicit planner tag or command_type table."""
    explicit = _coerce_stop_zone(stop_zone_tag)
    if explicit is not None:
        return explicit
    return COMMAND_STOP_ZONES.get(str(command_type or "").strip().lower())


def classify_command(
    command_type: str,
    *,
    stop_zone_tag: StopZone | str | None = None,
    risk_level: str = "medium",
) -> tuple[StopZone | None, ConfirmType]:
    """Classify a command into stop-zone + required confirm type."""
    zone = resolve_stop_zone(command_type, stop_zone_tag=stop_zone_tag)
    if zone is not None:
        return zone, confirm_type_for_stop_zone(zone)

    normalized_risk = str(risk_level or "medium").strip().lower()
    if normalized_risk in {"high", "critical"}:
        return None, ConfirmType.MODAL
    if normalized_risk == "medium":
        return None, ConfirmType.MODAL
    return None, ConfirmType.NONE
