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

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

import django


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

        result = dispatch.get_dictionary_values("holidays")
        self.day_infos = {}
        for item in result.get("children", None):
            label = item.get("label", "")
            start_end = item.get("value", "").replace("to", "至").split("至")
            if len(start_end) == 2:
                start_day = start_end[0].strip()  # 添加 strip() 去除空白字符
                end_day = start_end[1].strip()  # 添加 strip() 去除空白字符
                if start_day and end_day:
                    daterange_days = self.daterange(start_day, end_day)
                    self.day_infos.update({label: daterange_days})
            else:
                self.day_infos.update({label: start_end})

    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", "sobase.settings")
    django.setup()

    h = Holiday()
    h.today()
