"""IMA Stage 1 — Classification (Local Heuristic).

Filters out trivial content before it reaches expensive processing stages.
Uses keyword heuristics and pattern matching — zero API cost.
Expected to eliminate ~60-70% of incoming content.
"""

import re
import logging

logger = logging.getLogger("soagila.ima.classifier")

# ── Trivial Patterns (reject) ────────────────────────────────────────────────

TRIVIAL_PATTERNS = [
    # Greetings
    r"^(hi|hello|hey|merhaba|selam|selamlar)\s*[!.?]*$",
    # Thanks
    r"^(thanks?|thank\s*you|teşekkür|sağol|eyvallah|tşk)\s*[!.?]*$",
    # Simple confirmations
    r"^(ok|okay|evet|hayır|yes|no|sure|alright|tamam|oldu|anladım|peki)\s*[!.?]*$",
    # Acknowledgements
    r"^(got\s*it|understood|I\s*see|hmm|ah|aha|okey)\s*[!.?]*$",
    # Very short (under 15 chars, no substance)
    r"^.{1,14}$",
    # Only emojis/punctuation
    r"^[\s\W]+$",
    # "devam" / "başla" / "geç" type commands
    r"^(devam|başla|geç|next|continue|go|start|skip)\s*[!.?]*$",
]

_trivial_compiled = [re.compile(p, re.IGNORECASE | re.UNICODE) for p in TRIVIAL_PATTERNS]

# ── High-Value Patterns (boost) ──────────────────────────────────────────────

HIGH_VALUE_KEYWORDS = [
    # Architecture
    "architecture", "database", "schema", "migration", "api", "endpoint",
    "framework", "stack", "infrastructure", "deploy", "docker", "kubernetes",
    # Decisions
    "decision", "chose", "decided", "selected", "switched", "migrated",
    "karar", "seçtik", "geçtik", "değiştirdik",
    # Bugs & Fixes
    "bug", "fix", "error", "crash", "issue", "root cause", "workaround",
    "hata", "düzeltme", "çözüm",
    # Config
    "config", "setting", "environment", "variable", "secret", "key",
    "ayar", "yapılandırma",
    # Security
    "security", "encryption", "auth", "token", "certificate", "vulnerability",
    "güvenlik", "şifreleme",
    # Performance
    "performance", "optimization", "latency", "memory", "cpu", "bottleneck",
    "performans", "optimizasyon",
    # User preferences
    "prefer", "always", "never", "style", "convention",
    "tercih", "her zaman", "asla",
]

# ── Content Categories ────────────────────────────────────────────────────────

CATEGORY_KEYWORDS = {
    "architecture": ["architecture", "schema", "database", "api", "endpoint", "stack",
                     "framework", "deploy", "infra", "mimari", "şema"],
    "bug_fix": ["bug", "fix", "error", "crash", "issue", "workaround", "root cause",
                "hata", "düzeltme", "çözüm"],
    "configuration": ["config", "setting", "env", "variable", "secret",
                      "ayar", "yapılandırma", "ortam"],
    "security": ["security", "encrypt", "auth", "token", "certificate", "vulnerability",
                 "güvenlik", "şifre"],
    "preference": ["prefer", "always", "never", "style", "convention", "want",
                   "tercih", "istemiyorum", "istiyorum"],
    "performance": ["performance", "optimization", "latency", "cache", "speed",
                    "performans", "optimizasyon", "hız"],
    "documentation": ["document", "readme", "comment", "explain", "description",
                      "dokümantasyon", "açıklama"],
}


class ClassificationResult:
    """Result of Stage 1 classification."""

    def __init__(
        self,
        is_trivial: bool,
        category: str,
        importance_hint: float,
        confidence: float,
        reason: str,
    ):
        self.is_trivial = is_trivial
        self.category = category
        self.importance_hint = importance_hint
        self.confidence = confidence
        self.reason = reason

    def to_dict(self) -> dict:
        return {
            "is_trivial": self.is_trivial,
            "category": self.category,
            "importance_hint": self.importance_hint,
            "confidence": self.confidence,
            "reason": self.reason,
        }


def classify(content: str) -> ClassificationResult:
    """Classify content using keyword heuristics. Zero API cost.

    Returns:
        ClassificationResult with is_trivial flag and category.
    """
    stripped = content.strip()

    # ── Check trivial patterns ────────────────────────────────────────────
    for pattern in _trivial_compiled:
        if pattern.match(stripped):
            logger.debug(f"IMA classifier: trivial match — '{stripped[:50]}...'")
            return ClassificationResult(
                is_trivial=True,
                category="trivial",
                importance_hint=0.0,
                confidence=0.95,
                reason="matched_trivial_pattern",
            )

    # ── Word count check ──────────────────────────────────────────────────
    words = stripped.split()
    word_count = len(words)

    if word_count < 5:
        # Very short but didn't match trivial — low confidence reject
        return ClassificationResult(
            is_trivial=True,
            category="trivial",
            importance_hint=0.1,
            confidence=0.6,
            reason="too_short",
        )

    # ── Check high-value keywords ─────────────────────────────────────────
    lower_content = stripped.lower()
    high_value_hits = sum(1 for kw in HIGH_VALUE_KEYWORDS if kw in lower_content)

    # ── Determine category ────────────────────────────────────────────────
    category_scores: dict[str, int] = {}
    for cat, keywords in CATEGORY_KEYWORDS.items():
        score = sum(1 for kw in keywords if kw in lower_content)
        if score > 0:
            category_scores[cat] = score

    if category_scores:
        category = max(category_scores, key=category_scores.get)  # type: ignore
    else:
        category = "general"

    # ── Compute importance hint ───────────────────────────────────────────
    importance = 0.3  # baseline

    # Boost for high-value keywords
    importance += min(high_value_hits * 0.1, 0.4)

    # Boost for longer content (more context = likely more important)
    if word_count > 50:
        importance += 0.1
    if word_count > 200:
        importance += 0.1

    # Boost for category match
    if category != "general":
        importance += 0.1

    importance = min(importance, 1.0)

    logger.debug(
        f"IMA classifier: category={category}, importance={importance:.2f}, "
        f"high_value_hits={high_value_hits}, words={word_count}"
    )

    return ClassificationResult(
        is_trivial=False,
        category=category,
        importance_hint=importance,
        confidence=0.8 if high_value_hits > 0 else 0.5,
        reason="keyword_classification",
    )
