from __future__ import annotations

import sqlite3
from pathlib import Path
from typing import Any, Dict, List, Optional

from store_schedule_lib.meta import meta_float, meta_int

try:
    import yaml
except ImportError:  # pragma: no cover
    yaml = None  # type: ignore

SKILL_ROOT = Path(__file__).resolve().parent.parent
CONFIG_DIR = SKILL_ROOT / "config"
REMINDER_RULES_PATH = CONFIG_DIR / "reminder_rules.yaml"
TASK_REGISTRY_PATH = CONFIG_DIR / "task_registry.yaml"
RECURRING_EVENTS_PATH = CONFIG_DIR / "store_recurring_events.yaml"

DEFAULT_RULES: Dict[str, Any] = {
    "lead_minutes": {"appt": 30, "appt_urgent": 5, "birthday": 0},
    "scan": {
        "daily_digest_cron": "30 7 * * *",
        "daily_plan_cron": "45 7 * * *",
        "daily_plan_at": "07:45",
        "tz": "Asia/Shanghai",
    },
    "thresholds": {
        "card_expiring_days": 30,
        "member_due_days": 30,
        "balance_low": 500.0,
    },
    "schedule_kinds": ["birthday", "member_due", "card_expiring", "follow_up", "appt"],
    "messages": {
        "birthday": "客户 {name} 今天生日，记得祝福或回访。",
        "appt": "预约提醒：{member_name} {service} {start_dt}，{lead} 分钟后开始。",
        "member_due": "客户 {name} 将于 {date} 到期，请提前联系。",
        "card_expiring": "会员 {member_name} 的次卡「{card_name}」将于 {expire_date} 到期。",
        "follow_up": "记得跟进会员 {name}。",
    },
}

DEPRECATED_KINDS = frozenset({"dynamic_due"})


def _load_yaml(path: Path) -> Dict[str, Any]:
    if yaml is None or not path.is_file():
        return {}
    with open(path, encoding="utf-8") as f:
        data = yaml.safe_load(f) or {}
    return data if isinstance(data, dict) else {}


def load_reminder_rules() -> Dict[str, Any]:
    rules = dict(DEFAULT_RULES)
    file_rules = _load_yaml(REMINDER_RULES_PATH)
    for key, val in file_rules.items():
        if isinstance(val, dict) and isinstance(rules.get(key), dict):
            merged = dict(rules[key])
            merged.update(val)
            rules[key] = merged
        else:
            rules[key] = val
    return rules


def load_task_registry() -> List[Dict[str, Any]]:
    data = _load_yaml(TASK_REGISTRY_PATH)
    tasks = data.get("tasks", [])
    return tasks if isinstance(tasks, list) else []


def load_recurring_events() -> List[Dict[str, Any]]:
    data = _load_yaml(RECURRING_EVENTS_PATH)
    events = data.get("events", [])
    return events if isinstance(events, list) else []


def schedule_kinds() -> List[str]:
    return list(load_reminder_rules().get("schedule_kinds", DEFAULT_RULES["schedule_kinds"]))


def validate_schedule_kinds(kinds: List[str]) -> Optional[str]:
    for k in kinds:
        if k in DEPRECATED_KINDS:
            return "reminder_kind_deprecated"
        if k not in schedule_kinds():
            return "invalid_reminder_kind"
    return None


def threshold_int(conn: sqlite3.Connection, key: str, default: int) -> int:
    yaml_default = int(load_reminder_rules().get("thresholds", {}).get(key, default))
    return meta_int(conn, key, yaml_default)


def threshold_float(conn: sqlite3.Connection, key: str, default: float) -> float:
    yaml_default = float(load_reminder_rules().get("thresholds", {}).get(key, default))
    return meta_float(conn, key, yaml_default)


def lead_minutes_for(kind: str) -> int:
    rules = load_reminder_rules()
    lead = rules.get("lead_minutes", {})
    return int(lead.get(kind, lead.get("appt", 30)))
