"""Production policy helpers — grants, routing, stop-zones (0.2.2.45)."""

from __future__ import annotations

import re
from typing import Any

from .stop_zone import StopZone

VISION_COMMAND_TYPES = frozenset(
    {
        "capture_screenshot",
        "verify_screen_contains_text",
        "describe_active_window",
        "verify_web_draft",
        "verify_published",
        "open_web_composer",
    }
)

PUBLISH_COMMAND_TYPES = frozenset(
    {
        "social_post_publish",
        "browser_click_publish",
        "email_send",
        "message_send",
        "comment_submit",
        "mass_mail_send",
        "public_accusation_post",
    }
)

_PUBLISH_SUBMIT_VERB_RE = re.compile(
    r"\b(?:"
    r"publish|published|publishing|"
    r"send|sending|sent|"
    r"submit|submitted|submitting|"
    r"опубликовать|опубликуй|опубликован|"
    r"отправить|отправь|отправлен|"
    r"post\s+publicly|submit\s+button"
    r")\b",
    re.IGNORECASE,
)

_PUBLISH_NEGATION_RE = re.compile(
    r"\b(?:"
    r"не\s+опублик|без\s+опублик|не\s+жми|не\s+отправ|"
    r"don't\s+publish|do\s+not\s+publish|draft\s+only|"
    r"без\s+отправ|черновик\s+только"
    r")\b",
    re.IGNORECASE,
)


def is_vision_command(command_type: str) -> bool:
    return str(command_type or "").strip().lower() in VISION_COMMAND_TYPES


def is_publish_command_type(command_type: str) -> bool:
    return str(command_type or "").strip().lower() in PUBLISH_COMMAND_TYPES


def payload_requests_submit(payload: dict[str, Any] | None) -> bool:
    data = payload or {}
    return bool(
        data.get("submit_after")
        or data.get("submit_message")
        or data.get("press_enter")
    )


def is_publish_submit_action(command_type: str, payload: dict[str, Any] | None = None) -> bool:
    ctype = str(command_type or "").strip().lower()
    if is_publish_command_type(ctype):
        return True
    data = payload or {}
    stop = str(data.get("stop_zone") or "").strip().lower()
    if stop == StopZone.PUBLISH.value:
        return True
    if ctype == "keyboard_type_text" and payload_requests_submit(data):
        return True
    return False


def step_text_indicates_publish_submit(text: str) -> bool:
    raw = str(text or "")
    if not raw.strip():
        return False
    if _PUBLISH_NEGATION_RE.search(raw):
        return False
    return bool(_PUBLISH_SUBMIT_VERB_RE.search(raw))


def resolve_publish_stop_zone_tag(
    command_type: str,
    payload: dict[str, Any] | None = None,
    *,
    step_text: str = "",
) -> StopZone | None:
    if is_publish_submit_action(command_type, payload):
        return StopZone.PUBLISH
    # Do not tag unrelated plan steps (browser_open_url, vision, typing) just because
    # goal_summary / reasoning_summary mentions «опубликуй».
    if is_publish_command_type(command_type) and step_text_indicates_publish_submit(step_text):
        return StopZone.PUBLISH
    return None


def screen_vision_denial_message() -> str:
    return (
        "permission_denied:screen_vision_grant_required — "
        "включите «Видение экрана» (screen_vision) в Центре разрешений"
    )


def root_operations_denial_message() -> str:
    return (
        "permission_denied:root_operations_grant_required — "
        "включите «Root-операции» (root_operations) в Центре разрешений"
    )


def routing_write_denial_message(*, hint: str = "") -> str:
    base = "permission_denied:path_outside_routing_scope"
    if hint:
        return f"{base} — {hint}"
    return base


def stamp_post_confirm_execution_flags(
    payload: dict[str, Any],
    *,
    stop_zone: str | None = None,
    command_type: str = "",
) -> None:
    """Mark payload after user confirmed stop-zone / publish / root actions."""
    if stop_zone == StopZone.PUBLISH.value or is_publish_submit_action(command_type, payload):
        payload["publish_confirmed"] = True
    if str(payload.get("execution_profile") or "user").strip().lower() == "root":
        payload["root_confirmed"] = True
