"""
Zubbl Task Utilities

Shared task normalization used by both API and RL Worker.
Single source of truth to avoid API/worker mismatch.
"""

import hashlib

# Priority-ordered patterns (first match wins as primary category)
_TASK_PATTERNS = [
    ("debug", "debugging"),
    ("fix bug", "bugfix"),
    ("fix", "bugfix"),
    ("refactor", "refactoring"),
    ("deploy", "deployment"),
    ("test", "testing"),
    ("search", "search"),
    ("analyze", "analysis"),
    ("summarize", "summarization"),
    ("translate", "translation"),
    ("classify", "classification"),
    ("detect", "detection"),
    ("generate", "generation"),
    ("write", "writing"),
    ("code", "coding"),
    ("api", "api_work"),
    ("database", "database_work"),
    ("db ", "database_work"),
    ("sql", "database_work"),
    ("file", "file_operations"),
    ("image", "image_processing"),
    ("parse", "parsing"),
    ("validate", "validation"),
    ("optimize", "optimization"),
]

# Words to ignore when building context hash
_STOP_WORDS = frozenset(
    {
        "a",
        "an",
        "the",
        "to",
        "for",
        "in",
        "on",
        "with",
        "my",
        "your",
        "is",
        "and",
        "or",
        "of",
        "that",
        "this",
        "it",
        "be",
        "do",
        "does",
        "was",
        "were",
        "been",
        "being",
        "have",
        "has",
        "had",
        "will",
        "can",
        "could",
        "would",
        "should",
        "not",
        "but",
        "so",
        "if",
        "then",
        "about",
        "from",
        "by",
        "at",
        "into",
        "through",
        "during",
        "before",
        "after",
        "above",
        "below",
        "between",
        "each",
        "every",
        "some",
        "any",
        "all",
        "both",
        "few",
        "more",
        "most",
        "other",
        "such",
        "no",
        "only",
        "own",
        "same",
        "than",
        "too",
        "very",
        "just",
        "also",
        "how",
        "what",
        "which",
        "who",
        "when",
        "where",
        "why",
        "please",
        "help",
        "me",
        "i",
    }
)


def normalize_task_type(task: str) -> str:
    """
    Normalize a task description to a task type.

    Uses priority-first-match for the primary category,
    plus a context hash from significant words for sub-categorization.

    Examples:
        "debug the auth API" → "debugging_8a3f2c"
        "write unit tests"   → "writing_b4e1d9"
        "fix SQL timeout"    → "bugfix_c7a3e2"

    Two different tasks in the same category produce different types:
        "write documentation" → "writing_a1b2c3"
        "write unit tests"    → "writing_d4e5f6"
    """
    task_lower = task.lower().strip()

    # Find primary category (first match wins)
    primary_category = None
    for keyword, category in _TASK_PATTERNS:
        if keyword in task_lower:
            primary_category = category
            break

    if not primary_category:
        # Fallback: hash first few words for unknown task types
        words = task_lower.split()[:5]
        return "general_" + hashlib.md5("_".join(words).encode()).hexdigest()[:8]

    # Add context hash from significant words for sub-categorization
    significant = [w for w in task_lower.split() if w not in _STOP_WORDS and len(w) > 2]
    context_hash = hashlib.md5("_".join(significant[:5]).encode()).hexdigest()[:6]

    return f"{primary_category}_{context_hash}"


def hash_task(task: str) -> str:
    """Create a stable hash of a task description"""
    return hashlib.sha256(task.strip().lower().encode()).hexdigest()[:16]
