"""Info, stats, utility, and notes handlers — Persian v5.1."""
from __future__ import annotations

import asyncio
import logging
from datetime import datetime
from typing import Optional

from telegram import Update
from telegram.constants import ParseMode
from telegram.error import BadRequest
from telegram.ext import CommandHandler, ContextTypes

from bot import db
from bot.decorators import admin_only
from bot.helpers import resolve_target, user_link
from bot.persian_router import register_mixed

logger = logging.getLogger(__name__)


async def whois_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    target = await resolve_target(context.bot, update.message)
    if not target:
        await update.message.reply_text(user_link(update.effective_user, str(update.effective_user.id)),
                                         parse_mode=ParseMode.HTML)
        return
    try:
        user = await context.bot.get_chat(target)
        text = f"اطلاعات کاربر:\n\n"
        text += f"نام: {user.first_name or '?'}\n"
        if user.last_name:
            text += f"نام خانوادگی: {user.last_name}\n"
        if user.username:
            text += f"یوزرنیم: @{user.username}\n"
        text += f"آیدی: <code>{user.id}</code>\n"
        text += f"لینک: tg://user?id={user.id}\n"
        bio = getattr(user, "bio", None)
        if bio:
            text += f"بیو: {bio}\n"
        await update.message.reply_text(text, parse_mode=ParseMode.HTML)
    except BadRequest:
        await update.message.reply_text("این کاربر رو پیدا نکردم!")


async def id_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    chat = update.effective_chat
    text = f"شناسه‌ها:\n\n"
    text += f"شما: <code>{user.id}</code>\n"
    if chat.type != "private":
        text += f"گروه: <code>{chat.id}</code>\n"
        if update.message.reply_to_message and update.message.reply_to_message.from_user:
            ru = update.message.reply_to_message.from_user
            text += f"کاربر ریپلای شده: <code>{ru.id}</code>\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def info_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    target = await resolve_target(context.bot, update.message) or update.effective_user.id
    try:
        user = await context.bot.get_chat(target)
    except BadRequest:
        await update.message.reply_text("این کاربر رو پیدا نکردم!")
        return
    warns = await db.get_warns_count(chat.id, target)
    nickname = await db.get_nickname(chat.id, target)
    vip = await db.vip_check(chat.id, target)
    text = f"اطلاعات کاربر:\n\n"
    text += f"نام: {user.first_name or '?'}\n"
    if user.last_name:
        text += f"نام خانوادگی: {user.last_name}\n"
    if user.username:
        text += f"یوزرنیم: @{user.username}\n"
    text += f"آیدی: <code>{user.id}</code>\n"
    text += f"تعداد اخطار: {warns}\n"
    if nickname:
        text += f"لقب: {nickname}\n"
    if vip:
        text += "کاربر ویژه: ✅\n"
    bio = getattr(user, "bio", None)
    if bio:
        text += f"بیو: {bio}\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def me_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    chat = update.effective_chat
    text = f"اطلاعات شما:\n\n"
    text += f"نام: {user.first_name or '?'}\n"
    if user.last_name:
        text += f"نام خانوادگی: {user.last_name}\n"
    if user.username:
        text += f"یوزرنیم: @{user.username}\n"
    text += f"آیدی: <code>{user.id}</code>\n"
    if chat.type != "private":
        warns = await db.get_warns_count(chat.id, user.id)
        msgs = (await db.get_top_users(chat.id, 9999))
        my_msgs = next((m["msg_count"] for m in msgs if m["user_id"] == user.id), 0)
        nickname = await db.get_nickname(chat.id, user.id)
        text += f"تعداد پیام‌ها: {my_msgs}\n"
        text += f"تعداد اخطار: {warns}\n"
        if nickname:
            text += f"لقب: {nickname}\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def chatinfo_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    if chat.type == "private":
        await update.message.reply_text("این دستور فقط تو گروه کار میکنه!")
        return
    try:
        full = await context.bot.get_chat(chat.id)
    except BadRequest:
        return
    text = f"اطلاعات گروه:\n\n"
    text += f"نام: {full.title}\n"
    text += f"آیدی: <code>{full.id}</code>\n"
    if full.username:
        text += f"یوزرنیم: @{full.username}\n"
    text += f"نوع: {full.type}\n"
    if full.member_count:
        text += f"اعضا: {full.member_count} نفر\n"
    if full.description:
        text += f"توضیحات: {full.description}\n"
    if full.invite_link:
        text += f"لینک دعوت: {full.invite_link}\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def stats_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    top = await db.get_top_users(chat.id, 10)
    total_msgs = sum(t["msg_count"] for t in top)
    text = f"آمار گروه:\n\n"
    text += f"مجموع پیام‌های ثبت شده: {total_msgs}\n\n"
    if top:
        text += "فعال‌ترین کاربران:\n"
        medals = ["🥇", "🥈", "🥉"]
        for i, t in enumerate(top):
            medal = medals[i] if i < 3 else f"{i+1}."
            try:
                u = await context.bot.get_chat(t["user_id"])
                name = u.first_name or str(t["user_id"])
            except BadRequest:
                name = str(t["user_id"])
            text += f"{medal} <a href='tg://user?id={t['user_id']}'>{name}</a> - {t['msg_count']} پیام\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def top_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await stats_cmd(update, context)


async def ping_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    start = asyncio.get_event_loop().time()
    msg = await update.message.reply_text("در حال بررسی ...")
    end = asyncio.get_event_loop().time()
    ms = int((end - start) * 1000)
    status = "عالی" if ms < 200 else "خوب" if ms < 500 else "قابل قبول" if ms < 1000 else "ضعیف"
    await msg.edit_text(
        f"سرعت اتصال:\n"
        f"{ms} میلی‌ثانیه ({status})"
    )


async def save_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    msg = update.message
    args = (msg.text or "").split(maxsplit=1)
    if len(args) < 2:
        await msg.reply_text("روی یه پیام ریپلای کن و بگو: ذخیره کن [نام]")
        return
    name = args[1].lower()
    if msg.reply_to_message:
        content = msg.reply_to_message.text or msg.reply_to_message.caption or ""
        file_id, file_type = None, None
        if msg.reply_to_message.photo:
            file_id = msg.reply_to_message.photo[-1].file_id
            file_type = "photo"
        elif msg.reply_to_message.video:
            file_id = msg.reply_to_message.video.file_id
            file_type = "video"
        elif msg.reply_to_message.voice:
            file_id = msg.reply_to_message.voice.file_id
            file_type = "voice"
        elif msg.reply_to_message.document:
            file_id = msg.reply_to_message.document.file_id
            file_type = "document"
        elif msg.reply_to_message.sticker:
            file_id = msg.reply_to_message.sticker.file_id
            file_type = "sticker"
        await db.save_note(update.effective_chat.id, name, content, file_id, file_type)
    else:
        await db.save_note(update.effective_chat.id, name, args[1])
    await msg.reply_text(f"یادداشت «{name}» ذخیره شد! برای دیدنش بگو: {name}")


async def get_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    args = (update.message.text or "").split(maxsplit=1)
    if len(args) < 2:
        await update.message.reply_text("بگو: دریافت [نام] یا #[نام]")
        return
    name = args[1].lower()
    note = await db.get_note(update.effective_chat.id, name)
    if not note:
        await update.message.reply_text(f"یادداشت «{name}» پیدا نشد!")
        return
    file_id = note["file_id"]
    file_type = note["file_type"]
    if file_id and file_type:
        fn = getattr(context.bot, f"send_{file_type}", None)
        if fn:
            kwargs = {file_type: file_id, "chat_id": update.effective_chat.id}
            if note["content"]:
                kwargs["caption"] = note["content"]
            try:
                await fn(**kwargs)
                return
            except BadRequest:
                pass
    if note["content"]:
        await update.message.reply_text(note["content"], parse_mode=ParseMode.HTML)


async def notes_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    notes = await db.get_all_notes(update.effective_chat.id)
    if not notes:
        await update.message.reply_text("هنوز یادداشتی ذخیره نشده!")
        return
    text = f"یادداشت‌ها ({len(notes)}):\n\n"
    text += ", ".join(f"<code>#{n}</code>" for n in notes[:30])
    text += "\n\nبرای دیدن هر کدوم بگو: دریافت [نام]"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


@admin_only
async def clear_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    args = (update.message.text or "").split(maxsplit=1)
    if len(args) < 2:
        await update.message.reply_text("بگو: حذف یادداشت [نام]")
        return
    await db.delete_note(update.effective_chat.id, args[1].lower())
    await update.message.reply_text(f"یادداشت حذف شد!")


@admin_only
async def clearall_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await db.delete_all_notes(update.effective_chat.id)
    await update.message.reply_text("همه یادداشت‌ها پاک شدن!")


async def getpro_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    args = (update.message.text or "").split()
    target = await resolve_target(context.bot, update.message) or update.effective_user.id
    n = int(args[1]) if len(args) > 1 and args[1].isdigit() else 1
    try:
        photos = await context.bot.get_user_profile_photos(target, limit=min(n, 200))
    except BadRequest:
        await update.message.reply_text("کاربر رو پیدا نکردم!")
        return
    if not photos.photos:
        await update.message.reply_text("این کاربر عکس پروفایل نداره!")
        return
    if n > photos.total_count:
        await update.message.reply_text(f"فقط {photos.total_count} تا عکس داره!")
        return
    photo = photos.photos[n - 1][-1]
    await context.bot.send_photo(
        update.effective_chat.id,
        photo.file_id,
        caption=f"پروفایل {n}/{photos.total_count}",
    )


async def whois_alias_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    args = (update.message.text or "").split()
    if len(args) >= 2 and args[1].lstrip("-").isdigit():
        target = int(args[1])
        try:
            user = await context.bot.get_chat(target)
            await update.message.reply_text(
                f"کاربر: {user.first_name}\n"
                f"آیدی: <a href='tg://user?id={target}'>پروفایل</a>",
                parse_mode=ParseMode.HTML,
            )
        except BadRequest:
            await update.message.reply_text("کاربر رو پیدا نکردم!")
    else:
        await whois_cmd(update, context)


async def linkmsg_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    reply = update.message.reply_to_message
    if not reply:
        await update.message.reply_text("روی پیامی که می‌خوای لینکشو بگیری ریپلای کن!")
        return
    chat = update.effective_chat
    if chat.username:
        link = f"https://t.me/{chat.username}/{reply.message_id}"
    else:
        link = f"https://t.me/c/{str(chat.id).replace('-100', '')}/{reply.message_id}"
    await update.message.reply_text(
        f"لینک پیام:\n<a href='{link}'>{link}</a>",
        parse_mode="HTML",
        disable_web_page_preview=True,
    )


def register(app) -> None:
    register_mixed(
        app,
        {
            "id": id_cmd,
            "me": me_cmd,
            "whois": whois_cmd,
            "info": info_cmd,
            "chatinfo": chatinfo_cmd,
            "gpinfo": chatinfo_cmd,
            "ping": ping_cmd,
            "save": save_cmd,
            "get": get_cmd,
            "notes": notes_cmd,
            "clear": clear_cmd,
            "clearall": clearall_cmd,
            "stats": stats_cmd,
            "top": top_cmd,
            "getpro": getpro_cmd,
            "linkmsg": linkmsg_cmd,
        },
        {
            "آیدی": id_cmd,
            "ایدی": id_cmd,
            "آیدی من": id_cmd,
            "آیدی گروه": chatinfo_cmd,
            "من": me_cmd,
            "اطلاعات من": me_cmd,
            "وویس": whois_cmd,
            "اطلاعات کاربر": info_cmd,
            "مشخصات کاربر": info_cmd,
            "اطلاعات گروه": chatinfo_cmd,
            "مشخصات گروه": chatinfo_cmd,
            "پینگ": ping_cmd,
            "چه خبر": ping_cmd,
            "وضعیت اتصال": ping_cmd,
            "ذخیره": save_cmd,
            "ذخیره کن": save_cmd,
            "ذخیره یادداشت": save_cmd,
            "دریافت": get_cmd,
            "دریافت یادداشت": get_cmd,
            "یادداشت": notes_cmd,
            "یادداشت‌ها": notes_cmd,
            "همه یادداشت": notes_cmd,
            "لیست یادداشت": notes_cmd,
            "حذف یادداشت": clear_cmd,
            "پاک کردن یادداشت": clear_cmd,
            "حذف همه یادداشت": clearall_cmd,
            "پاک کردن همه یادداشت": clearall_cmd,
            "آمار": stats_cmd,
            "آمار گروه": stats_cmd,
            "فعالترین": top_cmd,
            "فعال‌ترین": top_cmd,
            "برترین": top_cmd,
            "کاربران برتر": top_cmd,
            "فعال ترین ها": top_cmd,
            "دریافت پروفایل": getpro_cmd,
            "پروفایل": getpro_cmd,
            "عکس پروفایل": getpro_cmd,
            "لینک پیام": linkmsg_cmd,
            "لینک": linkmsg_cmd,
            "گرفتن لینک": linkmsg_cmd,
            "لینک بگیر": linkmsg_cmd,
        },
    )
