"""
Rule Generator — converts natural-language user input into policy rules.

No external LLM required for MVP: uses keyword matching.
Can be extended later to call OpenAI for richer parsing.

Examples:
  "Always remember my deployment setup"
    → store: ["deployment", "workflow"]

  "Don't store debugging steps"
    → ignore: ["debug", "temporary"]

  "Remember everything about this project"
    → store: ["success_task", "workflow", "preference", "decision", "observation"]
"""

import re
from typing import Dict, Any, List

# Keyword → policy bucket mappings
STORE_KEYWORDS = {
    "deploy": ["workflow", "success_task"],
    "deployment": ["workflow", "success_task"],
    "workflow": ["workflow"],
    "preference": ["preference"],
    "decision": ["decision"],
    "success": ["success_task"],
    "everything": ["success_task", "workflow", "preference", "decision", "observation"],
    "all": ["success_task", "workflow", "preference", "decision", "observation"],
    "project": ["success_task", "workflow", "preference", "decision"],
    "setup": ["workflow", "preference"],
    "config": ["preference", "workflow"],
    "experience": ["workflow"],
}

IGNORE_KEYWORDS = {
    "debug": ["temporary", "failed"],
    "debugging": ["temporary", "failed"],
    "failed": ["failed"],
    "failure": ["failed"],
    "error": ["failed"],
    "temporary": ["temporary"],
    "noise": ["noise"],
    "step": ["temporary"],
    "intermediate": ["temporary"],
    "nothing": ["success_task", "workflow", "preference", "decision"],
}


def generate_rules_from_text(text: str) -> Dict[str, Any]:
    """
    Parse a natural-language policy description into structured rules.

    Returns:
        {
            "store": [...],
            "ignore": [...],
            "scope": "global" | "session",
            "raw_input": text,
            "confidence": 0.0–1.0,
        }
    """
    text_lower = text.lower().strip()
    store_buckets: List[str] = []
    ignore_buckets: List[str] = []

    is_negative = bool(re.search(r"\b(don't|dont|do not|never|stop|ignore|skip)\b", text_lower))
    is_positive = bool(re.search(r"\b(always|remember|store|keep|save|track)\b", text_lower))

    if is_negative:
        for kw, buckets in IGNORE_KEYWORDS.items():
            if kw in text_lower:
                ignore_buckets.extend(buckets)
        if not ignore_buckets:
            for kw, buckets in STORE_KEYWORDS.items():
                if kw in text_lower:
                    ignore_buckets.extend(buckets)
    elif is_positive:
        for kw, buckets in STORE_KEYWORDS.items():
            if kw in text_lower:
                store_buckets.extend(buckets)

    store_buckets = list(dict.fromkeys(store_buckets))
    ignore_buckets = list(dict.fromkeys(ignore_buckets))

    scope = "session" if re.search(r"\bthis\s+(session|task|conversation)\b", text_lower) else "global"
    confidence = 0.8 if (store_buckets or ignore_buckets) else 0.2

    return {
        "store": store_buckets,
        "ignore": ignore_buckets,
        "scope": scope,
        "raw_input": text,
        "confidence": confidence,
    }
