from borax.calendars import LunarDate
from nonebot import on_command
from nonebot.internal.adapter.event import Event
from nonebot_plugin_alconna import UniMessage
from nonebot_plugin_apscheduler import scheduler

from konabot.common.subscribe import PosterInfo, register_poster_info, broadcast

register_poster_info(
    "二十四节气",
    PosterInfo(
        {"节气", "24节气"},
        "当有新的节气时，报告节气信息",
    ),
)

# 二十四节气的内置口号
# Generated by claude-opus-4.6
SOLAR_TERM_SLOGANS: dict[str, str] = {
    "立春": "春回大地，万物复苏！",
    "雨水": "春雨绵绵，润物无声！",
    "惊蛰": "春雷惊蛰，万物生长！",
    "春分": "昼夜平分，春意盎然！",
    "清明": "清明时节，踏青赏春！",
    "谷雨": "谷雨时节，播种希望！",
    "立夏": "立夏之日，夏意渐浓！",
    "小满": "小满时节，麦穗渐满！",
    "芒种": "芒种农忙，收获在望！",
    "夏至": "夏至日长，骄阳似火！",
    "小暑": "小暑炎炎，清凉为伴！",
    "大暑": "大暑酷热，防暑降温！",
    "立秋": "立秋时节，暑去凉来！",
    "处暑": "处暑时节，秋高气爽！",
    "白露": "白露降临，秋意渐浓！",
    "秋分": "秋分时节，硕果累累！",
    "寒露": "寒露凝结，秋意正浓！",
    "霜降": "霜降时节，秋收冬藏！",
    "立冬": "立冬之日，冬意渐起！",
    "小雪": "小雪飘飘，寒意渐浓！",
    "大雪": "大雪纷飞，银装素裹！",
    "冬至": "冬至日短，数九寒天！",
    "小寒": "小寒时节，天寒地冻！",
    "大寒": "大寒岁末，辞旧迎新！",
}


@scheduler.scheduled_job("cron", hour="8")
async def _():
    today = LunarDate.today()
    term: str | None = today.term

    if term is not None:
        slogan = SOLAR_TERM_SLOGANS.get(term, "")
        await broadcast(
            "二十四节气", UniMessage.text(f"【今日节气】今天是 {term} 哦！{slogan}")
        )


cmd_next_term = on_command("下一个节气")


@cmd_next_term.handle()
async def _(event: Event):
    date = LunarDate.today()
    day_counter = 0

    while date.term is None:
        date = date.after(day_delta=1)
        day_counter += 1
        if day_counter > 365:
            await UniMessage.text("哇呀...查询出错了！").send(event)
            return

    d_cn_format = date.strftime("%M月%D")  # 相当于正月初一这样的格式
    date_solar = date.to_solar_date()
    d_glob_format = f"{date_solar.month} 月 {date_solar.day} 日"
    msg = UniMessage.text(
        f"下一个节气是{date.term}，在 {day_counter} 天后的 {d_glob_format}（农历{d_cn_format}）"
    )
    await msg.send(event)


cmd_current_term = on_command("当前节气", aliases={"获取节气", "节气"})


@cmd_current_term.handle()
async def _(event: Event):
    date = LunarDate.today()
    day_counter = 0

    while date.term is None:
        date = date.before(day_delta=1)
        day_counter += 1
        if day_counter > 365:
            await UniMessage.text("哇呀...查询出错了！").send(event)
            return

    msg = UniMessage.text(f"现在的节气是{date.term}")
    await msg.send(event)
