"""Auto daily stats — scheduled posts of group statistics.

Commands:
- /setautostat HH:MM — schedule daily stats at given time
- /remautostat — remove the scheduled stats
- /autostat — manually post stats now
"""
from __future__ import annotations

import logging
from datetime import datetime

from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, ContextTypes

from bot import db
from bot.decorators import admin_only
from bot.persian_router import register_mixed
from bot.handlers.utility import generate_stats_text

logger = logging.getLogger(__name__)


@admin_only
async def set_autostat_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    args = (update.message.text or "").split()
    if len(args) < 2:
        await update.message.reply_text("ℹ️ فرمت: /setautostat HH:MM (مثلاً 09:00)")
        return
    try:
        parts = args[1].split(":")
        hour, minute = int(parts[0]), int(parts[1])
    except (ValueError, IndexError):
        await update.message.reply_text("❌ زمان نامعتبر. از فرمت HH:MM استفاده کنید.")
        return
    await db.update_setting(chat.id, "autostat_time", args[1])
    await update.message.reply_text(f"✅ آمار روزانه ساعت {args[1]} تنظیم شد.")


@admin_only
async def rem_autostat_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    await db.update_setting(chat.id, "autostat_time", "")
    await update.message.reply_text("✅ آمار روزانه لغو شد.")


@admin_only
async def autostat_now_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    text = await generate_stats_text(context.bot, chat.id)
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


def register_jobs(application: Application) -> None:
    """Register the autostat job to run every 60 seconds."""
    async def _check_and_send(context):
        from bot import db
        from bot.handlers.utility import generate_stats_text
        chats = await db.get_autostat_chats()
        for chat_id, t in chats:
            try:
                parts = t.split(":")
                target_hour, target_min = int(parts[0]), int(parts[1])
                current = datetime.now()
                if current.hour == target_hour and current.minute == target_min:
                    text = await generate_stats_text(context.bot, chat_id)
                    await context.bot.send_message(chat_id, text, parse_mode="HTML")
            except Exception as e:
                logger.warning("Autostat job error for %s: %s", chat_id, e)

    application.job_queue.run_repeating(_check_and_send, interval=60, first=30, name="autostat_check")
    logger.info("Autostat check job registered (every 60s)")


def register(app) -> None:
    register_mixed(
        app,
        {
            "setautostat": set_autostat_cmd,
            "remautostat": rem_autostat_cmd,
            "autostat": autostat_now_cmd,
        },
        {
            "تنظیم آمار خودکار": set_autostat_cmd,
            "حذف آمار خودکار": rem_autostat_cmd,
            "آمار": autostat_now_cmd,
        },
    )
