"""FOLDER_ANALYSIS intent — desktop/folder content reports (not device diagnostics)."""

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Any, Literal

from .capability_resolver import FolderScope, resolve_folder_scope, resolve_user_folder

FolderAnalysisDepth = Literal["shallow", "recursive"]

_FOLDER_ANALYSIS_VERBS_RE = re.compile(
    r"\b(?:анализ\w*|analyze|analysis|обзор\w*|провед\w*|изуч\w*)\b",
    re.IGNORECASE,
)
_FOLDER_CONTENT_RE = re.compile(
    r"\b(?:содержим\w*|content|что\s+(?:на|в|лежит)|список\s+файл|list\s+files?|files?\s+on)\b",
    re.IGNORECASE,
)
_DESKTOP_CONTENT_RE = re.compile(
    r"\b(?:что\s+на\s+рабоч\w*\s+стол|what(?:'s| is)\s+on\s+(?:the\s+)?desktop|"
    r"список\s+файл\w*\s+на\s+рабоч\w*\s+стол)\b",
    re.IGNORECASE,
)
_DESKTOP_ANALYSIS_SHORT_RE = re.compile(
    r"\b(?:анализ\w*|analyze|analysis|обзор\w*)\w*\s+(?:рабоч\w*\s+стол|desktop)\b",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class FolderAnalysisIntent:
    intent: Literal["FOLDER_ANALYSIS"] = "FOLDER_ANALYSIS"
    location: FolderScope | str = "unknown"
    location_path: str = ""
    depth: FolderAnalysisDepth = "recursive"
    policy_hint: str = ""
    user_term: str = ""

    def as_dict(self) -> dict[str, Any]:
        return {
            "intent": self.intent,
            "location": self.location,
            "location_path": self.location_path,
            "depth": self.depth,
            "policy_hint": self.policy_hint,
            "user_term": self.user_term,
        }


def _mentions_screen_not_folder(text: str) -> bool:
    """True when the user means the live screen, not a filesystem folder."""
    lower = str(text or "").strip().lower()
    if not lower:
        return False
    if re.search(r"\b(?:что\s+на\s+экран|what(?:'s| is)\s+on\s+(?:the\s+)?screen)\b", lower):
        if not re.search(r"\b(?:рабоч\w*\s+стол|desktop)\b", lower):
            return True
    if re.search(r"\b(?:активн\w*\s+окн|active\s+window|текущ\w*\s+окн)\b", lower):
        return True
    return False


def is_folder_analysis_intent(text: str) -> bool:
    """FOLDER_ANALYSIS — analyze folder/desktop contents, never CPU/RAM diagnostics."""
    raw = str(text or "").strip()
    if not raw:
        return False

    from .compound_intent_resolver import should_defer_folder_analysis

    if should_defer_folder_analysis(raw):
        return False

    from ..ui.avatar_intent_router import is_active_window_analysis_intent

    if is_active_window_analysis_intent(raw):
        return False
    if _mentions_screen_not_folder(raw):
        return False

    from .local_search_resolver import is_local_search_intent

    if is_local_search_intent(raw):
        return False

    if re.search(
        r"\b(?:процессор|cpu|загрузк\w*\s+процессор|оператив|ram|памят|диск|disk|место на диске|озу)\b",
        raw,
        re.IGNORECASE,
    ):
        if not re.search(r"\b(?:содержим|файл|files?|desktop|рабоч)\b", raw, re.IGNORECASE):
            return False

    if _DESKTOP_CONTENT_RE.search(raw):
        return True
    if _DESKTOP_ANALYSIS_SHORT_RE.search(raw):
        return True

    has_analysis = bool(_FOLDER_ANALYSIS_VERBS_RE.search(raw))
    has_content = bool(_FOLDER_CONTENT_RE.search(raw))
    scope = resolve_folder_scope(raw)
    has_location = scope != "unknown" or bool(
        re.search(r"\b(?:рабоч\w*|desktop|папк|folder|директор|каталог|загрузк|documents?|документ)\b", raw, re.I)
    )

    if has_content and has_location:
        return True
    if has_analysis and (has_content or has_location):
        return True
    return False


def parse_folder_analysis_intent(text: str) -> FolderAnalysisIntent | None:
    raw = str(text or "").strip()
    if not is_folder_analysis_intent(raw):
        return None

    scope = resolve_folder_scope(raw)
    if scope == "unknown":
        scope = "desktop"

    resolved = resolve_user_folder(raw, scope=scope, for_read=True)
    if resolved is None:
        return None

    lower = raw.lower()
    depth: FolderAnalysisDepth = "recursive"
    if any(token in lower for token in ("только верхн", "без подпап", "shallow", "top level", "верхний уровень")):
        depth = "shallow"

    return FolderAnalysisIntent(
        location=resolved.scope,
        location_path=str(resolved.path),
        depth=depth,
        policy_hint=resolved.policy_hint,
        user_term=resolved.user_term,
    )


def build_folder_analysis_plan(text: str) -> dict[str, Any] | None:
    """Build list_files_in_folder plan with folder_analysis report mode."""
    intent = parse_folder_analysis_intent(text)
    if intent is None:
        return None

    location_label = {
        "desktop": "рабочего стола",
        "downloads": "Загрузок",
        "documents": "Документов",
        "pictures": "Изображений",
        "home": "домашней папки",
        "workspace": "IuVeWorkspace",
    }.get(str(intent.location), str(intent.location))

    payload: dict[str, Any] = {
        "absolute_path": intent.location_path,
        "pattern": "*",
        "action": "folder_analysis",
        "recursive": intent.depth == "recursive",
        "max_entries": 500,
        "user_folder_scope": str(intent.location),
        "policy_hint": intent.policy_hint,
        "folder_analysis_intent": intent.as_dict(),
        "user_consent_state": "consented_via_connect_flow",
    }

    steps: list[dict[str, Any]] = [
        {
            "step_id": "s1",
            "command_type": "list_files_in_folder",
            "payload": payload,
        }
    ]

    plan: dict[str, Any] = {
        "goal_summary": f"Полный анализ содержимого {location_label}",
        "steps": steps,
    }
    if intent.policy_hint:
        plan["policy_hint"] = intent.policy_hint
    return plan


def folder_entity_signals(text: str) -> list:
    """Minimal bridge: expose folder/file location entities for Orchestra registry."""
    raw = str(text or "").strip()
    if not raw:
        return []

    try:
        from app.services.orchestra.entity_registry import EntityRecord
    except ImportError:
        return []

    intent = parse_folder_analysis_intent(raw)
    if intent is None:
        scope = resolve_folder_scope(raw)
        if scope == "unknown":
            return []
        location = scope
        location_path = ""
        user_term = scope
    else:
        location = intent.location
        location_path = intent.location_path
        user_term = intent.user_term or str(location)

    entity_id = f"folder:{location}"
    return [
        EntityRecord(
            id=entity_id,
            type="folder",
            aliases=[str(user_term), str(location)],
            confidence=0.74,
            source="folder_resolver",
            label=f"Folder: {location}",
            relations=[{"kind": "path", "target": location_path}] if location_path else [],
        )
    ]
