import datetime
from typing import cast

from astrbot.api import logger

from ..services import CalendarDay, CalendarWeekday, RenderData
from .base_renderer import BaseRenderer
from .pillow.calendar_card import draw_calendar_card


def reorder_days(calendar_data: list[CalendarDay]) -> list[CalendarDay]:
    today_id = datetime.datetime.now().isoweekday()
    today_index = 0
    for i, day in enumerate(calendar_data):
        weekday: CalendarWeekday = day.get("weekday", {})
        if weekday.get("id") == today_id:
            today_index = i
            day["is_today"] = True
            break
    return calendar_data[today_index:] + calendar_data[:today_index]


class CalendarRenderer(BaseRenderer):
    async def render_calendar(
        self,
        calendar_data: list[CalendarDay],
        rpc_url: str | None = None,
        headless: bool = True,
        max_retries: int = 3,
    ) -> str | None:
        try:
            reordered_days = reorder_days(calendar_data)
        except (ValueError, TypeError, RuntimeError) as e:
            logger.error(f"[-] 处理日历数据失败: {e}")
            return None

        render_data = cast(RenderData, {"days": reordered_days})
        return await self.render(
            template_path="calendar/calendar.html",
            render_data=render_data,
            selector=".container",
            local_render_func=lambda: draw_calendar_card(render_data, self._session),
            rpc_url=rpc_url,
            sub_dir="calendar",
            timeout=30000,
            wait_time=0,
        )
