"""Detect local text-editor (notepad/gedit) intents — not web composer (0.2.2.56 DEF-002)."""

from __future__ import annotations

import re

from .explicit_text_extractor import extract_explicit_post_text

_NOTEPAD_TOKENS = (
    "блокнот",
    "notepad",
    "gedit",
    "kate",
    "текстовый редактор",
    "text editor",
    "notes",
    "заметк",
)
_NOTEPAD_WRITE_RE = re.compile(
    r"(?:напиш\w*|write|введ\w*|type)\s+(?:в\s+)?(?:блокнот\w*|notepad|gedit|kate|текстов\w+\s+редактор\w*)",
    re.IGNORECASE,
)
_NOTEPAD_TEXT_TAIL_RE = re.compile(
    r"(?:текст|text)\s+(.+)$",
    re.IGNORECASE,
)
_QUOTED_RE = re.compile(r"[«\"']([^»\"']{1,240})[»\"']")


def is_local_notepad_intent(text: str) -> bool:
    """True when user wants to type into a local text editor, not a web post composer."""
    raw = str(text or "").strip()
    if not raw:
        return False
    lower = raw.lower()
    if any(token in lower for token in _NOTEPAD_TOKENS):
        if any(verb in lower for verb in ("напиш", "write", "введ", "type", "текст", "text", "открой")):
            return True
    return bool(_NOTEPAD_WRITE_RE.search(raw))


def extract_notepad_text(text: str) -> str:
    """Extract verbatim body for local notepad typing."""
    raw = str(text or "").strip()
    if not raw:
        return ""

    explicit = extract_explicit_post_text(raw)
    if explicit:
        return explicit

    tail = _NOTEPAD_TEXT_TAIL_RE.search(raw)
    if tail:
        candidate = str(tail.group(1) or "").strip(" .,:;—–-»\"'")
        if candidate and len(candidate) <= 240:
            return candidate

    quoted = _QUOTED_RE.search(raw)
    if quoted:
        return str(quoted.group(1) or "").strip()

    colon_match = re.search(
        r"(?:напиш\w*|write)\s*[:—–-]\s*(.+)$",
        raw,
        re.IGNORECASE,
    )
    if colon_match:
        return str(colon_match.group(1) or "").strip(" .,:;—–-»\"'")
    return ""
