"""Central intent priority resolution (0.2.2.50 taxonomy).

Order: explicit prompt > exact text > URL/path > output format > action verb >
conversation context > goal memory > defaults.
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Any, Literal

PriorityTier = Literal[
    "explicit_prompt",
    "exact_text",
    "url_path",
    "output_format",
    "action_verb",
    "conversation_context",
    "goal_memory",
    "default",
]


class RootIntent(str, Enum):
    TEXT_RESPONSE = "TEXT_RESPONSE"
    PLAN_ONLY = "PLAN_ONLY"
    DEVICE_ACTION = "DEVICE_ACTION"
    DEVICE_TASK = "DEVICE_TASK"
    ARTIFACT_GENERATION = "ARTIFACT_GENERATION"
    DOCUMENT_GENERATION = "DOCUMENT_GENERATION"
    CODE_GENERATION = "CODE_GENERATION"
    WEB_OPERATOR = "WEB_OPERATOR"
    WEB_RESEARCH = "WEB_RESEARCH"
    RESEARCH_THEN_ARTIFACT = "RESEARCH_THEN_ARTIFACT"
    JOB_SEARCH = "JOB_SEARCH"
    LOCAL_SEARCH = "LOCAL_SEARCH"
    FOLDER_ANALYSIS = "FOLDER_ANALYSIS"
    VISION_ANALYSIS = "VISION_ANALYSIS"
    SYSTEM_DIAGNOSTICS = "SYSTEM_DIAGNOSTICS"
    DEVICE_STATUS_QUERY = "DEVICE_STATUS_QUERY"
    MEMORY_QUERY = "MEMORY_QUERY"
    EXACT_TEXT_INPUT = "EXACT_TEXT_INPUT"
    ADVISORY = "ADVISORY"
    META_EXTERNAL = "META_EXTERNAL"


@dataclass(frozen=True)
class RootIntentResolution:
    root_intent: RootIntent
    subtype: str = ""
    priority_tier: PriorityTier = "default"
    matched_rule: str = ""
    generate_content: bool | None = None
    exact_text: str = ""


def resolve_root_intent(
    text: str,
    *,
    memory_context: dict[str, Any] | None = None,
    conversation_context: str = "",
) -> RootIntentResolution:
    """Classify NL into canonical root intent using strict priority rules."""
    raw = str(text or "").strip()
    if not raw:
        return RootIntentResolution(RootIntent.TEXT_RESPONSE, matched_rule="empty_prompt")

    # Local-first canonical mappings (flag-gated) — prevent weather/news/FX/time/calc misroutes.
    try:
        from app.services.local_first import flags as _lf_flags
        from app.services.local_first.intent_matchers import root_intent_override_payload

        if _lf_flags.skill_contracts_enabled() or _lf_flags.tools_enabled():
            override = root_intent_override_payload(raw)
            if override and float(override.get("confidence") or 0) >= 0.85:
                family = str(override.get("skill_family") or "")
                root = RootIntent.WEB_RESEARCH if family in {"weather", "news", "currency"} else RootIntent.TEXT_RESPONSE
                return RootIntentResolution(
                    root,
                    subtype=str(override.get("canonical_intent") or ""),
                    priority_tier="explicit_prompt",
                    matched_rule=str(override.get("matched_rule") or "local_first"),
                )
    except Exception:
        pass

    from iuve_connect_agents.desktop.ui.avatar_intent_router import (
        classify_avatar_request_type,
        is_active_window_analysis_intent,
        is_folder_analysis_intent,
        is_job_search_intent,
        is_local_search_intent,
        is_plan_only_intent,
        is_web_research_intent,
        wants_screen_verification,
    )
    from iuve_connect_agents.desktop.active.artifact_generation_intent import (
        detect_artifact_generation_intent,
        is_code_generation_intent,
    )
    from iuve_connect_agents.desktop.active.content_creation_intent import (
        is_document_generation_intent as is_doc_gen,
        is_web_post_intent,
    )
    from iuve_connect_agents.desktop.active.device_status_query_intent import is_device_status_query_intent
    from iuve_connect_agents.desktop.active.explicit_text_extractor import extract_explicit_post_intent
    from iuve_connect_agents.desktop.active.memory_query_intent import (
        is_file_location_query,
        is_memory_query_intent,
    )
    from iuve_connect_agents.desktop.active.website_resolver import prompt_specifies_site
    try:
        from iuve_connect_agents.desktop.active.web_research_resolver import (
            is_research_then_artifact_intent,
            is_web_research_intent as is_web_research_resolver_intent,
        )
    except ImportError:
        is_research_then_artifact_intent = lambda _t: False  # type: ignore[assignment,misc]
        is_web_research_resolver_intent = is_web_research_intent

    request_type = classify_avatar_request_type(raw)
    if request_type == "capabilities_faq":
        return RootIntentResolution(RootIntent.ADVISORY, subtype="capabilities_faq", priority_tier="explicit_prompt")
    if request_type == "meta_external":
        return RootIntentResolution(RootIntent.META_EXTERNAL, priority_tier="explicit_prompt")

    if is_plan_only_intent(raw):
        return RootIntentResolution(RootIntent.PLAN_ONLY, priority_tier="explicit_prompt", matched_rule="plan_only_tokens")

    explicit = extract_explicit_post_intent(raw)
    if explicit and explicit.exact_text and not explicit.generate_content:
        return RootIntentResolution(
            RootIntent.EXACT_TEXT_INPUT,
            priority_tier="exact_text",
            matched_rule="explicit_literal_text",
            generate_content=False,
            exact_text=explicit.exact_text,
        )

    if is_research_then_artifact_intent(raw):
        return RootIntentResolution(
            RootIntent.RESEARCH_THEN_ARTIFACT,
            priority_tier="output_format",
            matched_rule="dossier_internet_compound",
        )

    try:
        from iuve_connect_agents.desktop.active.local_notepad_intent import is_local_notepad_intent

        if is_local_notepad_intent(raw):
            return RootIntentResolution(
                RootIntent.DEVICE_TASK,
                subtype="local_notepad",
                priority_tier="explicit_prompt",
                matched_rule="local_notepad_text_editor",
            )
    except ImportError:
        pass

    if is_doc_gen(raw):
        return RootIntentResolution(
            RootIntent.DOCUMENT_GENERATION,
            priority_tier="output_format",
            matched_rule="document_md_or_form",
        )

    artifact = detect_artifact_generation_intent(raw)
    if artifact:
        root = RootIntent.CODE_GENERATION if is_code_generation_intent(raw) else RootIntent.ARTIFACT_GENERATION
        return RootIntentResolution(
            root,
            subtype=artifact.subtype,
            priority_tier="output_format",
            matched_rule="artifact_file_request",
        )

    if is_device_status_query_intent(raw):
        return RootIntentResolution(
            RootIntent.DEVICE_STATUS_QUERY,
            priority_tier="explicit_prompt",
            matched_rule="agent_status_query",
        )

    if is_memory_query_intent(raw) or is_file_location_query(raw):
        subtype = "file_location" if is_file_location_query(raw) else "session_recall"
        return RootIntentResolution(
            RootIntent.MEMORY_QUERY,
            priority_tier="explicit_prompt",
            matched_rule="session_memory_recall",
            subtype=subtype,
        )

    if is_active_window_analysis_intent(raw) or (
        wants_screen_verification(raw) and not is_doc_gen(raw)
    ):
        return RootIntentResolution(
            RootIntent.VISION_ANALYSIS,
            priority_tier="action_verb",
            matched_rule="vision_or_active_window",
        )

    if is_local_search_intent(raw):
        return RootIntentResolution(RootIntent.LOCAL_SEARCH, priority_tier="action_verb")

    if is_folder_analysis_intent(raw):
        return RootIntentResolution(RootIntent.FOLDER_ANALYSIS, priority_tier="action_verb")

    if is_job_search_intent(raw):
        return RootIntentResolution(RootIntent.JOB_SEARCH, priority_tier="action_verb", subtype="job_search")

    if is_web_research_resolver_intent(raw):
        return RootIntentResolution(RootIntent.WEB_RESEARCH, priority_tier="action_verb")

    if is_web_research_intent(raw):
        return RootIntentResolution(RootIntent.WEB_RESEARCH, priority_tier="action_verb")

    mem = dict(memory_context or {})
    prompt_has_site = prompt_specifies_site(raw)
    memory_site = str(mem.get("active_site") or mem.get("current_target_site") or "")
    if is_web_post_intent(raw, memory_site=memory_site if not prompt_has_site else ""):
        tier: PriorityTier = "explicit_prompt" if prompt_has_site else "goal_memory"
        if explicit and explicit.generate_content:
            return RootIntentResolution(
                RootIntent.WEB_OPERATOR,
                subtype="social_post",
                priority_tier=tier,
                matched_rule="web_post_topic_generation",
                generate_content=True,
            )
        return RootIntentResolution(
            RootIntent.WEB_OPERATOR,
            subtype="social_post",
            priority_tier=tier,
            matched_rule="web_post",
            generate_content=bool(explicit.generate_content) if explicit else True,
        )

    from iuve_connect_agents.desktop.ui.avatar_intent_router import detect_compound_intent

    compound = detect_compound_intent(raw)
    if compound.is_compound:
        return RootIntentResolution(
            RootIntent.DEVICE_TASK,
            priority_tier="action_verb",
            matched_rule="compound_categories",
            subtype=",".join(compound.categories_matched[:4]),
        )

    try:
        from iuve_connect_agents.desktop.ui.avatar_chat import is_diagnostics_query

        if is_diagnostics_query(raw):
            return RootIntentResolution(RootIntent.SYSTEM_DIAGNOSTICS, priority_tier="action_verb")
    except ImportError:
        pass

    if conversation_context.strip():
        return RootIntentResolution(
            RootIntent.TEXT_RESPONSE,
            priority_tier="conversation_context",
            matched_rule="fallback_with_context",
        )

    return RootIntentResolution(RootIntent.TEXT_RESPONSE, priority_tier="default", matched_rule="unclassified")
