"""Artifact and code file generation intents (0.2.2.50 taxonomy)."""

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Literal

from .content_creation_intent import is_document_generation_intent, is_html_landing_intent, is_web_post_intent

ArtifactSubtype = Literal["code", "document", "generic"]

_ARTIFACT_OUTPUT_RE = re.compile(
    r"\b(?:выдай|выдать|отдай|save\s+as|сохрани\s+как|download|скачать|"
    r"создай\s+файл|create\s+file|положи\s+в\s+файл|as\s+a\s+file)\b",
    re.IGNORECASE,
)
_CODE_FILE_RE = re.compile(
    r"\b[\w.-]+\.(?:html?|css|js|jsx|ts|tsx|py|php|json|xml|zip|csv|sh|rb|go)\b",
    re.IGNORECASE,
)
_CODE_TOPIC_TOKENS = (
    "код",
    "code",
    "скрипт",
    "script",
    "календар",
    "calendar",
    "widget",
    "landing",
    "лендинг",
    "html",
    "css",
    "javascript",
    "python",
    "php",
    "утилит",
    "utility",
    "приложен",
    "app ",
)
_FILENAME_FROM_PROMPT_RE = re.compile(
    r"\b([A-Za-z0-9_.-]+\.(?:html?|css|js|jsx|ts|tsx|py|php|md|json|xml|zip|csv))\b",
    re.IGNORECASE,
)
_CALENDAR_RE = re.compile(r"\b(?:календар\w*|calendar)\b", re.IGNORECASE)


@dataclass(frozen=True)
class ArtifactGenerationIntent:
    subtype: ArtifactSubtype
    topic: str
    output_filename: str
    content_type: str = "code"
    folder_name: str = "IuVeWorkspace"


def _has_create_verb(lower: str) -> bool:
    return any(
        token in lower
        for token in (
            "собери",
            "создай",
            "создать",
            "create ",
            "make ",
            "сделай",
            "напиши",
            "write ",
            "сгенерир",
            "generate",
        )
    )


def extract_artifact_filename(text: str, *, default: str = "artifact.html") -> str:
    match = _FILENAME_FROM_PROMPT_RE.search(str(text or ""))
    if match:
        return str(match.group(1) or "").strip() or default
    lower = str(text or "").strip().lower()
    if _CALENDAR_RE.search(lower):
        return "calendar.html"
    if "python" in lower or ".py" in lower:
        return "script.py"
    if "php" in lower:
        return "script.php"
    if "json" in lower:
        return "data.json"
    return default


def extract_artifact_topic(text: str, *, default: str = "artifact") -> str:
    raw = str(text or "").strip()
    lower = raw.lower()
    if _CALENDAR_RE.search(lower):
        return "simple HTML calendar"
    match = re.search(r"(?:о|об|про|about|for)\s+([^,.;]+)", lower)
    if match:
        topic = str(match.group(1) or "").strip()
        if topic and len(topic) > 2:
            return topic
    return default


def is_code_generation_intent(text: str) -> bool:
    """Code/HTML/JS/Python artifact — subclass of ARTIFACT_GENERATION."""
    if not is_artifact_generation_intent(text):
        return False
    if is_document_generation_intent(text):
        return False
    lower = str(text or "").strip().lower()
    if _CODE_FILE_RE.search(text):
        return True
    if any(token in lower for token in _CODE_TOPIC_TOKENS):
        return True
    if _CALENDAR_RE.search(lower):
        return True
    return False


def is_artifact_generation_intent(text: str) -> bool:
    """Create a file artifact in workspace — not plain chat or web post."""
    raw = str(text or "").strip()
    if not raw:
        return False
    if is_html_landing_intent(raw) or is_web_post_intent(raw):
        return False
    if is_document_generation_intent(raw):
        return False
    lower = raw.lower()
    if _ARTIFACT_OUTPUT_RE.search(raw):
        return True
    if _CODE_FILE_RE.search(raw) and _has_create_verb(lower):
        return True
    if _CALENDAR_RE.search(lower) and (
        _has_create_verb(lower) or "файл" in lower or "file" in lower or _ARTIFACT_OUTPUT_RE.search(raw)
    ):
        return True
    if _has_create_verb(lower) and _CODE_FILE_RE.search(raw):
        return True
    return False


def detect_artifact_generation_intent(text: str) -> ArtifactGenerationIntent | None:
    if not is_artifact_generation_intent(text):
        return None
    subtype: ArtifactSubtype = "code" if is_code_generation_intent(text) else "generic"
    filename = extract_artifact_filename(text)
    topic = extract_artifact_topic(text, default=filename.rsplit(".", 1)[0])
    content_type = "html_landing" if filename.lower().endswith((".html", ".htm")) else "code"
    if subtype == "code" and content_type != "html_landing":
        content_type = "code"
    return ArtifactGenerationIntent(
        subtype=subtype,
        topic=topic,
        output_filename=filename,
        content_type=content_type,
    )
