"""
Task Classifier — Identifies task type from input text.

PRD §6 — Task Type Recognition:
    Types: coding | deployment | research | planning | debugging

MVP: rule-based keyword matching.
Optional: LLM/embedding-based classification.
"""

import re
import logging
from typing import Optional

logger = logging.getLogger("openmemo.orchestrator")

TASK_TYPES = {"coding", "deployment", "research", "planning", "debugging"}

# Keyword maps per task type (PRD §6)
_PATTERNS = {
    "debugging": [
        r"\b(debug|error|bug|crash|fix|broken|fail|exception|traceback|stack trace)\b",
        r"\b(why (is|does|doesn.t)|not working|issue with)\b",
    ],
    "deployment": [
        r"\b(deploy|deployment|docker|compose|kubernetes|k8s|helm|release|ship|ci/cd|pipeline)\b",
        r"\b(build image|push image|rolling update|scale|replica|pod)\b",
    ],
    "coding": [
        r"\b(write|implement|build|create|code|function|class|module|api|endpoint)\b",
        r"\b(refactor|optimize|add feature|add a|extend)\b",
    ],
    "research": [
        r"\b(research|investigate|explore|analyze|study|survey|compare|review)\b",
        r"\b(what is|how does|tell me about|explain|summarize|overview)\b",
    ],
    "planning": [
        r"\b(plan|design|architect|strategy|roadmap|breakdown|scope|estimate|sprint)\b",
        r"\b(how (should|can) (i|we)|approach|steps to|checklist)\b",
    ],
}

# Priority order for tie-breaking
_TYPE_PRIORITY = ["debugging", "deployment", "coding", "planning", "research"]


class TaskClassifier:
    """
    Classifies a task string into one of the supported task types.

    Usage:
        clf = TaskClassifier()
        task_type = clf.classify("Deploy my FastAPI backend using docker-compose")
        # → "deployment"
    """

    def classify(self, task: str, agent_role: str = "") -> str:
        """
        Classify task text into a task type.

        Falls back to "coding" when nothing matches.
        agent_role hint can shift classification.
        """
        if not task:
            return self._from_role(agent_role)

        tl = task.lower()
        scores: dict[str, int] = {t: 0 for t in TASK_TYPES}

        for task_type, patterns in _PATTERNS.items():
            for pat in patterns:
                if re.search(pat, tl):
                    scores[task_type] += 1

        best_type = max(scores, key=lambda t: (scores[t], -_TYPE_PRIORITY.index(t)
                                                if t in _TYPE_PRIORITY else 999))

        if scores[best_type] == 0:
            return self._from_role(agent_role)

        logger.debug("classify task_type=%s scores=%s", best_type, scores)
        return best_type

    def _from_role(self, agent_role: str) -> str:
        """Infer task type from agent role hint."""
        role = agent_role.lower()
        if "debug" in role:
            return "debugging"
        if "deploy" in role or "devops" in role:
            return "deployment"
        if "research" in role or "analyst" in role:
            return "research"
        if "plan" in role or "architect" in role:
            return "planning"
        return "coding"  # safe default
