#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：django_base_ai
@File    ：holidays.py
@Author  ：congxing.wang
@Date    ：2026/02/25
@Desc    ：节假日判断工具
"""

import logging
import os
import sys
from datetime import datetime, timedelta
from pathlib import Path

import django

logger = logging.getLogger(__name__)


class Holiday:
    def __init__(self):
        from django_base_ai import dispatch

        result = dispatch.get_dictionary_values("holidays")
        self.day_infos = {}
        children = result.get("children") or []
        logger.debug("节假日配置加载 %d 条", len(children))
        for item in children:
            label = item.get("label", "")
            raw = (item.get("value") or "").replace("to", "至").strip()
            if not raw:
                continue
            if "至" in raw and raw.count("至") >= 1:
                start_end = raw.split("至")
                if len(start_end) >= 2:
                    start_day = start_end[0].strip()
                    end_day = start_end[1].strip()
                    if start_day and end_day:
                        daterange_days = self.daterange(start_day, end_day)
                        self.day_infos.update({label: daterange_days})
                    continue
            if "," in raw:
                days = [x.strip() for x in raw.split(",") if x.strip()]
                if days:
                    self.day_infos.update({label: days})
                continue
            self.day_infos.update({label: [raw]})

    def daterange(self, start_day, end_day):
        dates = []
        dt = datetime.strptime(start_day, "%Y-%m-%d")
        dt_end = datetime.strptime(end_day, "%Y-%m-%d")
        while dt <= dt_end:
            t = datetime.strftime(dt, "%Y-%m-%d")
            dates.append(t)
            dt += timedelta(1)
        return dates

    def today(self, day=None):
        day = str(datetime.today().date()) if day is None or day == "" else day
        holiday_title = [k for k, v in self.day_infos.items() if day in v]
        return {
            "is_holiday": True if len(holiday_title) else False,
            "holiday_title": holiday_title[0] if len(holiday_title) else "",
            "day": day,
        }


if __name__ == "__main__":
    BASE_DIR = f"{Path(__file__).resolve().parent.parent}"
    sys.path.append(BASE_DIR)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoBaseAi.settings")
    django.setup()

    h = Holiday()
    h.today()
