"""Policy Judge — bounded gate before execution (Phase D, rules-first)."""

from __future__ import annotations

from dataclasses import dataclass

from iuve_connect_agents.shared.confirm_type import ConfirmType
from iuve_connect_agents.shared.feature_flags import avatar_policy_judge_enabled, avatar_stop_zones_enabled
from iuve_connect_agents.shared.stop_zone import StopZone
from iuve_connect_agents.shared.stop_zone_policy import classify_command, resolve_stop_zone


@dataclass(frozen=True)
class PolicyJudgeResult:
    stop_zone: StopZone | None
    confirm_type: ConfirmType
    require_confirmation: bool
    reason_code: str = ""


class PolicyJudge:
    """Rules-first policy gate; never overrides hard deny from PolicyEngine."""

    def evaluate_step(
        self,
        command_type: str,
        *,
        stop_zone_tag: StopZone | str | None = None,
        risk_level: str = "medium",
    ) -> PolicyJudgeResult:
        if not avatar_policy_judge_enabled():
            return PolicyJudgeResult(
                stop_zone=None,
                confirm_type=ConfirmType.NONE,
                require_confirmation=False,
            )

        if not avatar_stop_zones_enabled():
            normalized_risk = str(risk_level or "medium").strip().lower()
            require = normalized_risk in {"medium", "high", "critical"}
            confirm = ConfirmType.MODAL if require else ConfirmType.NONE
            return PolicyJudgeResult(
                stop_zone=None,
                confirm_type=confirm,
                require_confirmation=require,
            )

        zone, confirm_type = classify_command(
            command_type,
            stop_zone_tag=stop_zone_tag,
            risk_level=risk_level,
        )
        if confirm_type == ConfirmType.DOUBLE_CONFIRM:
            return PolicyJudgeResult(
                stop_zone=zone,
                confirm_type=confirm_type,
                require_confirmation=True,
                reason_code=f"stop_zone:{zone.value if zone else 'unknown'}",
            )

        require = confirm_type in {ConfirmType.MODAL, ConfirmType.DOUBLE_CONFIRM}
        return PolicyJudgeResult(
            stop_zone=zone,
            confirm_type=confirm_type,
            require_confirmation=require,
        )

    @staticmethod
    def resolve_stop_zone(
        command_type: str,
        *,
        stop_zone_tag: StopZone | str | None = None,
    ) -> StopZone | None:
        return resolve_stop_zone(command_type, stop_zone_tag=stop_zone_tag)
