"""Plan Template Router — select plan template from atoms + DCM (Phase A)."""

from __future__ import annotations

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

from iuve_connect_agents.shared.intent_atomizer import AtomizedIntent, atomize_intent


class PlanTemplate(str, Enum):
    COMPOUND_SITE_LOCAL = "compound_site_local"
    WEB_POST = "web_post"
    FOLDER_ANALYSIS = "folder_analysis"
    SCREEN_CAPTURE = "screen_capture"
    DOCUMENT_GENERATION = "document_generation"
    WEB_RESEARCH = "web_research"
    WORKSPACE_FILES = "workspace_files"
    DEFAULT_RULES = "default_rules"


@dataclass(frozen=True)
class PlanRouteDecision:
    template: PlanTemplate
    reason: str
    atoms: AtomizedIntent
    dcm_available: bool


def route_plan_template(
    text: str,
    *,
    dcm: dict[str, Any] | None = None,
) -> PlanRouteDecision:
    """Choose plan template before building steps. Does not infer paths from NL."""
    atoms = atomize_intent(text)
    dcm_ok = isinstance(dcm, dict) and bool((dcm.get("paths") or {}))

    if atoms.requires_compound_plan:
        return PlanRouteDecision(
            template=PlanTemplate.COMPOUND_SITE_LOCAL,
            reason="browser+fs/document compound atoms",
            atoms=atoms,
            dcm_available=dcm_ok,
        )

    if any(a.kind == "screenshot.capture" for a in atoms.atoms):
        return PlanRouteDecision(
            template=PlanTemplate.SCREEN_CAPTURE,
            reason="screenshot.capture atom",
            atoms=atoms,
            dcm_available=dcm_ok,
        )

    if atoms.forbid_web_post and any(a.kind == "web.post" for a in atoms.atoms):
        return PlanRouteDecision(
            template=PlanTemplate.COMPOUND_SITE_LOCAL,
            reason="document.create blocks web.post",
            atoms=atoms,
            dcm_available=dcm_ok,
        )

    if any(a.kind == "web.post" for a in atoms.atoms) and not atoms.forbid_web_post:
        return PlanRouteDecision(
            template=PlanTemplate.WEB_POST,
            reason="explicit web.post atom",
            atoms=atoms,
            dcm_available=dcm_ok,
        )

    from iuve_connect_agents.desktop.active.folder_analysis_resolver import is_folder_analysis_intent

    if is_folder_analysis_intent(text) and not atoms.has_site and not atoms.requires_compound_plan:
        return PlanRouteDecision(
            template=PlanTemplate.FOLDER_ANALYSIS,
            reason="folder analysis without site compound",
            atoms=atoms,
            dcm_available=dcm_ok,
        )

    return PlanRouteDecision(
        template=PlanTemplate.DEFAULT_RULES,
        reason="fallback to legacy rule chain",
        atoms=atoms,
        dcm_available=dcm_ok,
    )
