"""Extract verbatim post body from user prompts (0.2.2.48 Web Post Operator)."""

from __future__ import annotations

import re
from dataclasses import dataclass

_PATH_CONTAMINATION_RE = re.compile(
    r"(?:/home/[^\s,»\"']+|шага:\s*[^\s,.»\"']+|IuVeWorkspace/[^\s,»\"']+)",
    re.IGNORECASE,
)

_QUOTED_CAPTURE = r"(?:[«\"']([^»\"']+)[»\"']|([^,;\n]+))"
_DELIMITER = r"[:—–-]\s*"

_EXPLICIT_PREFIXES = (
    r"напиш\w*",
    r"встав\w*",
    r"write",
    r"insert",
    r"текст",
    r"содержимое",
    r"со\s+следующим\s+текстом",
    r"с\s+текстом",
    r"post\s+text",
    r"напиш\w*\s+пост",
    r"опублику\w*",
)
_PREFIX_GROUP = r"(?:{})".format("|".join(_EXPLICIT_PREFIXES))

# «со словом: X» / «with the word: X» — exact body, no LLM invent
_WORD_LITERAL_RE = re.compile(
    r"(?:"
    r"со?\s+слов(?:ом|а|у)|"
    r"with\s+the\s+word|"
    r"using\s+the\s+word"
    r")\s*"
    rf"{_DELIMITER}{_QUOTED_CAPTURE}",
    re.IGNORECASE,
)
_EXPLICIT_COLON_RE = re.compile(
    rf"(?:{_PREFIX_GROUP})\s*{_DELIMITER}{_QUOTED_CAPTURE}",
    re.IGNORECASE,
)
_POST_WITH_TEXT_RE = re.compile(
    r"(?:создай|create|сделай|make)\s+пост\s+с\s+текстом\s*"
    rf"{_DELIMITER}{_QUOTED_CAPTURE}",
    re.IGNORECASE,
)
_POST_WITH_WORD_RE = re.compile(
    r"(?:напиш\w*|write|создай|create|сделай)\s+(?:пост|post)\s+"
    r"(?:со?\s+слов(?:ом|а)?|with\s+(?:the\s+)?word)\s*"
    rf"{_DELIMITER}{_QUOTED_CAPTURE}",
    re.IGNORECASE,
)
_EXACTLY_LITERAL_RE = re.compile(
    rf"(?:ровно|exactly|verbatim|буквально)\s*{_DELIMITER}{_QUOTED_CAPTURE}",
    re.IGNORECASE,
)
_WEB_POST_QUOTED_RE = re.compile(
    r"(?:пост|post|напиш\w*|write).{0,48}[«\"']([^»\"']+)[»\"']",
    re.IGNORECASE,
)
_ACTIVE_FIELD_RE = re.compile(
    r"напиш\w*\s+в\s+активн\w+\s+пол\w*\s*"
    rf"{_DELIMITER}{_QUOTED_CAPTURE}",
    re.IGNORECASE,
)
_TOPIC_POST_RE = re.compile(
    r"(?:напиш\w*|write)\s+пост\s+(?:о|об|про|about)\s+",
    re.IGNORECASE,
)
_TOPIC_ONLY_RE = re.compile(
    r"(?:пост|post)\s+(?:о|об|про|about)\s+",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class ExplicitTextIntent:
    exact_text: str
    generate_content: bool


def _sanitize_topic(text: str) -> str:
    cleaned = _PATH_CONTAMINATION_RE.sub("", str(text or "")).strip(" .,:;—–-»\"'")
    cleaned = re.sub(r"\s+", " ", cleaned).strip()
    if cleaned.lower().startswith("шага:"):
        cleaned = cleaned.split(":", 1)[-1].strip()
    if _PATH_CONTAMINATION_RE.search(cleaned) or cleaned.lower() in {"сайт", "site", "шага"}:
        return ""
    return cleaned


def _trim_tail(raw: str) -> str:
    cleaned = str(raw or "").strip()
    cleaned = re.sub(
        r"\s+и\s+(?:потом\s+)?нажми.*$",
        "",
        cleaned,
        flags=re.IGNORECASE,
    )
    cleaned = re.sub(
        r"\s+нажми\s+(?:кнопку\s+)?опубликовать.*$",
        "",
        cleaned,
        flags=re.IGNORECASE,
    )
    return cleaned.strip(" .,:;—–-»\"'")


def _accept_literal(candidate: str) -> str:
    cleaned = _sanitize_topic(_trim_tail(str(candidate or "")))
    if not cleaned:
        return ""
    if re.search(r"\b(?:пост|post|стать|article)\s+(?:о|об|про|about)\b", cleaned, re.IGNORECASE):
        return ""
    if _TOPIC_POST_RE.search(cleaned) or _TOPIC_ONLY_RE.search(cleaned):
        return ""
    return cleaned


def _match_groups(match: re.Match[str]) -> str:
    return str(match.group(1) or match.group(2) or "").strip()


def extract_explicit_post_intent(text: str) -> ExplicitTextIntent | None:
    """
    Priority: explicit literal text wins over topic generation.
    Returns None when the prompt is not a content/post request.
    """
    raw = str(text or "").strip()
    if not raw:
        return None

    for pattern in (
        _EXACTLY_LITERAL_RE,
        _POST_WITH_WORD_RE,
        _WORD_LITERAL_RE,
        _POST_WITH_TEXT_RE,
        _ACTIVE_FIELD_RE,
        _EXPLICIT_COLON_RE,
    ):
        match = pattern.search(raw)
        if match:
            accepted = _accept_literal(_match_groups(match))
            if accepted:
                return ExplicitTextIntent(exact_text=accepted, generate_content=False)

    quoted_match = _WEB_POST_QUOTED_RE.search(raw)
    if quoted_match:
        accepted = _accept_literal(str(quoted_match.group(1) or ""))
        if accepted:
            return ExplicitTextIntent(exact_text=accepted, generate_content=False)

    if _TOPIC_POST_RE.search(raw) or _TOPIC_ONLY_RE.search(raw):
        return ExplicitTextIntent(exact_text="", generate_content=True)

    return None


def extract_explicit_post_text(text: str) -> str:
    """Return verbatim post body when present, else empty string."""
    intent = extract_explicit_post_intent(text)
    if intent and intent.exact_text and not intent.generate_content:
        return intent.exact_text
    return ""


def should_generate_post_content(text: str) -> bool:
    """True when LLM should expand topic (no verbatim body in prompt)."""
    intent = extract_explicit_post_intent(text)
    if intent is None:
        return bool(re.search(r"\b(?:пост|post|напиш|write)\b", str(text or ""), re.IGNORECASE))
    return intent.generate_content
