"""统计服务：统一 TG 命令和 Web API 的统计口径"""
from __future__ import annotations

from datetime import datetime

from db.models import Action, Ban, Message
from services.time_utils import local_day_range


def day_range(day: str | None = None) -> tuple[str, datetime, datetime]:
    """返回当前应用时区的 (YYYY-MM-DD, start, end)。"""
    return local_day_range(day)


async def get_daily_stats(day: str | None = None, chat_id: int | None = None) -> dict:
    """获取单日统计。"""
    day_str, start, end = day_range(day)

    msg_q = Message.filter(created_at__gte=start, created_at__lt=end)
    spam_q = Message.filter(created_at__gte=start, created_at__lt=end, is_spam=True)
    ban_q = Ban.filter(created_at__gte=start, created_at__lt=end)
    total_ban_q = Ban.all()
    action_base = Action.filter(created_at__gte=start, created_at__lt=end)
    if chat_id is not None:
        msg_q = msg_q.filter(chat_id=chat_id)
        spam_q = spam_q.filter(chat_id=chat_id)
        ban_q = ban_q.filter(chat_id=chat_id)
        total_ban_q = total_ban_q.filter(chat_id=chat_id)
        action_base = action_base.filter(chat_id=chat_id)
    msg_count = await msg_q.count()
    spam_count = await spam_q.count()
    ban_count = await ban_q.count()
    total_bans = await total_ban_q.count()
    join_count = await action_base.filter(action="JOIN").count()
    leave_count = await action_base.filter(action="LEAVE").count()
    delete_count = await action_base.filter(action="DELETE").count()
    unban_count = await action_base.filter(action="UNBAN").count()

    return {
        "date": day_str,
        "messages": msg_count,
        "spam_messages": spam_count,
        "bans": ban_count,
        "today_bans": ban_count,
        "total_bans": total_bans,
        "joins": join_count,
        "leaves": leave_count,
        "deleted": delete_count,
        "unbans": unban_count,
        "chat_count": msg_count,
    }
