"""
事件分类器。

根据事件标题关键词判断类型（sport / meal / family / medical / appointment）。
分类规则从 config/reminder_rules.yaml 加载，支持运行时覆盖。
"""

from __future__ import annotations

import logging
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

import yaml

logger = logging.getLogger(__name__)

_DEFAULT_RULES_PATH = Path(__file__).parent.parent / "config" / "reminder_rules.yaml"

# yaml 不可用时的内置 fallback
_BUILTIN_KEYWORDS: dict[str, list[str]] = {
    "sport":       ["跑步", "晨跑", "健身", "游泳", "打球", "羽毛球", "乒乓球", "网球", "篮球", "足球", "瑜伽"],
    "meal":        ["聚餐", "饭局", "晚餐", "午餐", "火锅", "烧烤", "下午茶"],
    "family":      ["亲子", "接送", "接孩子", "送孩子", "家长会", "探望", "探亲", "回家"],
    "medical":     ["体检", "看病", "就医", "门诊", "复诊", "牙医", "口腔", "打疫苗"],
    "appointment": ["预约", "约定", "美发", "理发", "活动", "讲座", "展览", "旅行", "课程"],
}
_BUILTIN_DEFAULT = "appointment"


def _load_rules(path: Path) -> dict:
    try:
        with open(path, encoding="utf-8") as f:
            return yaml.safe_load(f) or {}
    except Exception as e:
        logger.warning(f"加载 reminder_rules.yaml 失败，使用内置规则: {e}")
        return {}


class EventClassifier:
    """
    事件分类器。

    用法：
        clf = EventClassifier()
        clf.classify("跑步晨练")   # → "sport"
        clf.classify("家庭聚餐")   # → "meal"
        clf.classify("牙医预约")   # → "medical"
        clf.classify("接孩子放学") # → "family"
        clf.classify("理发")       # → "appointment"
    """

    def __init__(
        self,
        rules_path: Path | None = None,
        keywords: dict[str, list[str]] | None = None,
        default_type: str | None = None,
    ):
        data = _load_rules(rules_path or _DEFAULT_RULES_PATH)

        # 优先级：外部传入 > yaml > 内置
        if keywords:
            self.keywords = keywords
        elif data.get("keywords"):
            self.keywords = {
                k: [str(w) for w in v]
                for k, v in data["keywords"].items()
            }
        else:
            self.keywords = _BUILTIN_KEYWORDS

        self.default_type: str = (
            default_type or data.get("default_type", _BUILTIN_DEFAULT)
        )

    def classify(self, summary: str, description: str = "") -> str:
        """
        返回事件类型：'sport' | 'meal' | 'family' | 'medical' | 'appointment'。
        按 sport → meal → family → medical → appointment 顺序匹配，匹配即返回。
        """
        text = (summary + " " + description).lower()
        for event_type in ("sport", "meal", "family", "medical", "appointment"):
            for kw in self.keywords.get(event_type, []):
                if kw.lower() in text:
                    return event_type
        return self.default_type


# 模块级默认实例，可直接 import 快速使用
_default: EventClassifier | None = None


def classify_event(summary: str, description: str = "") -> str:
    """模块级快捷函数，使用默认分类器（延迟初始化）。"""
    global _default
    if _default is None:
        _default = EventClassifier()
    return _default.classify(summary, description)
