"""Decision Engine: carga reglas en Markdown y evalúa condiciones."""
import os
import re
from datetime import datetime
import yaml


class DecisionEngine:
    def __init__(self):
        base = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
        self.escalation_rules = self.load_markdown(os.path.join(base, "logic", "escalation_rules.md"))
        self.calendar_rules = self.load_markdown(os.path.join(base, "config", "calendar_rules.md"))
        self.correlations = self.load_markdown(os.path.join(base, "logic", "correlations.md"))

    def load_markdown(self, filepath):
        with open(filepath, "r", encoding="utf-8") as f:
            content = f.read()
        yaml_blocks = re.findall(r"```yaml(.*?)```", content, re.DOTALL)
        rules = [yaml.safe_load(block) for block in yaml_blocks]
        return {"raw_markdown": content, "parsed_rules": rules}

    def evaluate_escalation(self, metric, value, context=None):
        context = context or {}
        for rule in self.escalation_rules["parsed_rules"]:
            condition = rule.get("Condición") or rule.get("Condition")
            if not condition:
                continue
            if self.matches_condition(condition, metric, value, context):
                return {
                    "level": self.extract_level(rule),
                    "message": rule.get("Mensaje") or rule.get("Message"),
                    "action": rule.get("Acción") or rule.get("Action"),
                }
        return None

    def matches_condition(self, condition, metric, value, context):
        condition = condition.replace("{count}", str(value))
        local_ctx = {"value": value, "metric": metric, **context}
        try:
            return eval(condition, {}, local_ctx)
        except Exception:
            return False

    def extract_level(self, rule):
        msg = (rule.get("Mensaje") or "").upper()
        if "🔥" in msg or "CRÍTICO" in msg:
            return "CRITICAL"
        if "🚨" in msg or "ALERT" in msg:
            return "ALERT"
        if "⚠️" in msg or "WARNING" in msg:
            return "WARNING"
        return "INFO"

    def adapt_to_calendar(self, event, reminder_type):
        # Placeholder simple: clasifica y aplica reglas básicas
        event_type = self.classify_event(event)
        if event_type == "MEETING" and reminder_type == "movement_break":
            return {"action": "postpone", "to": "event_end + 1min"}
        if event_type == "WORKOUT" and reminder_type == "movement_break":
            return {"action": "cancel"}
        return {"action": "send_normal"}

    def classify_event(self, event):
        title = (event.get("title") or "").lower()
        keywords = {
            "MEETING": ["meeting", "reunión", "call", "sync", "1:1"],
            "FOCUS": ["focus", "deep work", "coding", "writing"],
            "WORKOUT": ["gym", "workout", "calistenia", "ejercicio"],
            "MEAL": ["almuerzo", "cena", "desayuno", "lunch", "dinner"],
        }
        for event_type, kws in keywords.items():
            if any(kw in title for kw in kws):
                return event_type
        return "OTHER"

    def update_correlations(self, new_pattern):
        with open("logic/correlations.md", "a", encoding="utf-8") as f:
            f.write(f"\n## Correlación Detectada - {datetime.now().strftime('%Y-W%W')}\n")
            f.write(f"**Pattern:** {new_pattern['pattern']}\n")
            f.write(f"**Confidence:** {new_pattern['confidence']}%\n")
            f.write(f"**Action:** {new_pattern['action']}\n")
