"""Rule-based conversation classifier for six-dimension analysis."""

import re
from typing import Dict, Any, List

from .models import Conversation
from .rules import (
    QUESTION_PATTERNS,
    JUDGMENT_SIGNALS,
    DEEP_THINKING_KEYWORDS,
    NARRATIVE_KEYWORDS,
    OUTPUT_KEYWORDS,
)


def classify_question_level(prompt: str) -> str:
    """Classify question level: L4_Meta > L3_Why > L2_What > L1_How."""
    text = prompt[:300].lower()
    for level in ("L4_Meta", "L3_Why", "L2_What", "L1_How"):
        for pat in QUESTION_PATTERNS[level]:
            if re.search(pat, text):
                return level
    return "L1_How"


def detect_judgment(prompt: str) -> tuple:
    """Detect judgment signals. Returns (has_judgment, list_of_types)."""
    text = prompt[:300].lower()
    found_types = []
    for jtype, patterns in JUDGMENT_SIGNALS.items():
        for pat in patterns:
            if re.search(pat, text):
                found_types.append(jtype)
                break
    return (len(found_types) > 0, found_types)


def detect_deep_thinking(prompt: str) -> bool:
    """Detect deep thinking / reflection signals."""
    text = prompt[:300].lower()
    return any(kw in text for kw in DEEP_THINKING_KEYWORDS)


def detect_narrative(prompt: str) -> bool:
    """Detect narrative / writing signals."""
    text = prompt[:300].lower()
    return any(re.search(pat, text) for pat in NARRATIVE_KEYWORDS)


def detect_output(prompt: str) -> bool:
    """Detect output / hands-on signals (replaces cognitive_stage check)."""
    text = prompt[:300].lower()
    return any(re.search(pat, text) for pat in OUTPUT_KEYWORDS)


def classify_conversation(conv: Conversation) -> Dict[str, Any]:
    """Classify a single conversation across all dimensions."""
    prompt = conv.first_prompt

    has_judgment, judgment_types = detect_judgment(prompt)

    return {
        "question_level": classify_question_level(prompt),
        "has_judgment": has_judgment,
        "judgment_types": judgment_types,
        "has_deep_thinking": detect_deep_thinking(prompt),
        "has_narrative": detect_narrative(prompt),
        "has_output": detect_output(prompt),
    }


def classify_all(conversations: List[Conversation]) -> Dict[str, Dict[str, Any]]:
    """Classify all conversations. Returns {conv_id: classification}."""
    return {conv.id: classify_conversation(conv) for conv in conversations}
