"""Admin/promote/demote handler — custom mod list."""
from __future__ import annotations

import logging
from typing import Optional

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

from bot import db
from bot.config import OWNER_ID
from bot.decorators import admin_only
from bot.helpers import resolve_target, user_link
from bot.constants import E, MSG
from bot.persian_router import register_mixed

logger = logging.getLogger(__name__)

PROMOTE_KEY = "promote_list"


async def _is_promoted(chat_id: int, user_id: int) -> bool:
    lst = await db.get_setting(chat_id, PROMOTE_KEY, default=[])
    if not isinstance(lst, list):
        try:
            lst = list(lst)
        except TypeError:
            lst = []
    return user_id in lst


async def _add_promoted(chat_id: int, user_id: int) -> None:
    lst = await db.get_setting(chat_id, PROMOTE_KEY, default=[])
    if not isinstance(lst, list):
        lst = []
    if user_id not in lst:
        lst.append(user_id)
    await db.set_setting(chat_id, PROMOTE_KEY, lst)


async def _remove_promoted(chat_id: int, user_id: int) -> None:
    lst = await db.get_setting(chat_id, PROMOTE_KEY, default=[])
    if not isinstance(lst, list):
        lst = []
    if user_id in lst:
        lst.remove(user_id)
    await db.set_setting(chat_id, PROMOTE_KEY, lst)


async def _list_promoted(chat_id: int) -> list[int]:
    lst = await db.get_setting(chat_id, PROMOTE_KEY, default=[])
    if not isinstance(lst, list):
        return []
    return list(lst)





# ─────────────────────────── config ───────────────────────────
async def config_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Auto-add all current admins to the promote list."""
    chat = update.effective_chat
    user = update.effective_user
    if user.id != OWNER_ID and not await db.is_sudo(user.id):
        try:
            creator = await context.bot.get_chat_member(chat.id, user.id)
            if creator.status != "creator":
                await update.message.reply_text("❌ فقط سازنده گروه یا مالک ربات.")
                return
        except (BadRequest, Forbidden):
            await update.message.reply_text(MSG["error"])
            return

    try:
        admins = await context.bot.get_chat_administrators(chat.id)
    except (BadRequest, Forbidden):
        await update.message.reply_text(MSG["bot_admin"])
        return

    added = 0
    creator_id = None
    for admin in admins:
        if admin.status == "creator":
            creator_id = admin.user.id
            continue
        if admin.user.is_bot:
            continue
        if not await _is_promoted(chat.id, admin.user.id):
            await _add_promoted(chat.id, admin.user.id)
            added += 1

    creator_link = (
        f'<a href="tg://user?id={creator_id}">{creator_id}</a>' if creator_id else "?"
    )
    await update.message.reply_text(
        f"⚙️ پیکربندی انجام شد!\n\n"
        f"سازنده: {creator_link}\n"
        f"{added} ادمین جدید به لیست مدیران ربات اضافه شدند.",
        parse_mode=ParseMode.HTML,
    )


# ─────────────────────────── promote / demote ───────────────────────────
async def promote_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    user = update.effective_user
    if not user or not chat:
        return
    if user.id != OWNER_ID and not await db.is_sudo(user.id):
        try:
            member = await context.bot.get_chat_member(chat.id, user.id)
            if member.status != "creator":
                await update.message.reply_text("❌ فقط سازنده گروه یا مالک ربات میتواند مدیر اضافه کند.")
                return
        except (BadRequest, Forbidden):
            await update.message.reply_text(MSG["error"])
            return
    target = await resolve_target(context.bot, update.message)
    if not target:
        await update.message.reply_text(MSG["reply_or_user"])
        return
    if target == context.bot.id:
        await update.message.reply_text("به توپم دست نزن :)")
        return

    if await _is_promoted(chat.id, target):
        await update.message.reply_text(
            f"ℹ️ کاربر {user_link(None, str(target))} از قبل مدیر ربات است.",
            parse_mode=ParseMode.HTML,
        )
        return

    await _add_promoted(chat.id, target)
    await update.message.reply_text(
        f"➕ کاربر {user_link(None, str(target))} به لیست مدیران ربات اضافه شد.",
        parse_mode=ParseMode.HTML,
    )


async def demote_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    user = update.effective_user
    if not user or not chat:
        return
    if user.id != OWNER_ID and not await db.is_sudo(user.id):
        try:
            member = await context.bot.get_chat_member(chat.id, user.id)
            if member.status != "creator":
                await update.message.reply_text("❌ فقط سازنده گروه یا مالک ربات میتواند مدیر حذف کند.")
                return
        except (BadRequest, Forbidden):
            await update.message.reply_text(MSG["error"])
            return
    target = await resolve_target(context.bot, update.message)
    if not target:
        await update.message.reply_text(MSG["reply_or_user"])
        return
    if target == context.bot.id:
        return
    if not await _is_promoted(chat.id, target):
        await update.message.reply_text(
            f"ℹ️ کاربر {user_link(None, str(target))} مدیر ربات نیست.",
            parse_mode=ParseMode.HTML,
        )
        return
    await _remove_promoted(chat.id, target)
    await update.message.reply_text(
        f"➖ کاربر {user_link(None, str(target))} از لیست مدیران ربات حذف شد.",
        parse_mode=ParseMode.HTML,
    )


@admin_only
async def modlist_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    lst = await _list_promoted(chat.id)
    if not lst:
        await update.message.reply_text("📋 لیست مدیران ربات خالی است.")
        return
    text = f"📋 <b>لیست مدیران ربات ({len(lst)}):</b>\n\n"
    for i, uid in enumerate(lst, 1):
        text += f"{i}. <code>{uid}</code>\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


@admin_only
async def cleanmodlist_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    lst = await _list_promoted(chat.id)
    await db.set_setting(chat.id, PROMOTE_KEY, [])
    await update.message.reply_text(
        f"✅ لیست مدیران ربات پاک شد ({len(lst)} نفر حذف شدند)."
    )


# ─────────────────────────── Telegram admin management ───────────────────────────
@admin_only
async def addadmin_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """افزودن ادمین تلگرامی (promote in Telegram)"""
    chat = update.effective_chat
    target = await resolve_target(context.bot, update.message)
    if not target:
        await update.message.reply_text(MSG["reply_or_user"])
        return
    try:
        await context.bot.promote_chat_member(
            chat.id,
            target,
            can_change_info=True,
            can_delete_messages=True,
            can_invite_users=True,
            can_restrict_members=True,
            can_pin_messages=True,
            can_promote_members=False,
        )
        await update.message.reply_text(
            f"✅ کاربر {user_link(None, str(target))} به ادمین گروه ارتقا یافت.",
            parse_mode=ParseMode.HTML,
        )
    except (BadRequest, Forbidden) as e:
        await update.message.reply_text(f"{MSG['bot_no_perm']}\n{str(e)[:80]}")


@admin_only
async def rmadmin_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """عزل از ادمین تلگرامی"""
    chat = update.effective_chat
    target = await resolve_target(context.bot, update.message)
    if not target:
        await update.message.reply_text(MSG["reply_or_user"])
        return
    try:
        await context.bot.promote_chat_member(
            chat.id,
            target,
            can_change_info=False,
            can_delete_messages=False,
            can_invite_users=False,
            can_restrict_members=False,
            can_pin_messages=False,
            can_promote_members=False,
        )
        await update.message.reply_text(
            f"✅ کاربر {user_link(None, str(target))} از ادمینی عزل شد.",
            parse_mode=ParseMode.HTML,
        )
    except (BadRequest, Forbidden) as e:
        await update.message.reply_text(f"{MSG['bot_no_perm']}\n{str(e)[:80]}")


@admin_only
async def adminlist_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    try:
        admins = await context.bot.get_chat_administrators(chat.id)
    except (BadRequest, Forbidden):
        await update.message.reply_text(MSG["bot_admin"])
        return
    text = f"👮 <b>لیست ادمین‌های گروه ({len(admins)}):</b>\n\n"
    for i, admin in enumerate(admins, 1):
        u = admin.user
        name = f"@{u.username}" if u.username else f'<a href="tg://user?id={u.id}">{u.first_name}</a>'
        title = admin.custom_title or ""
        icon = "👑" if admin.status == "creator" else "🛡"
        text += f"{i}. {icon} {name} <code>{u.id}</code>"
        if title:
            text += f" - {title}"
        text += "\n"
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


# ─────────────────────────── Title (custom title for admins) ───────────────────────────
@admin_only
async def settitle_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat = update.effective_chat
    msg = update.message
    if not msg.reply_to_message or not msg.reply_to_message.from_user:
        await msg.reply_text(MSG["no_reply"])
        return
    args = (msg.text or "").split(maxsplit=1)
    if len(args) < 2:
        await msg.reply_text("❌ استفاده: روی پیام ریپلای کرده و بنویسید <code>settitle لقب</code>")
        return
    title = args[1][:16]  # max 16 chars
    target = msg.reply_to_message.from_user.id
    if target == context.bot.id:
        await msg.reply_text("به توپم دست نزن :)")
        return
    try:
        await context.bot.set_chat_administrator_custom_title(chat.id, target, title)
        await msg.reply_text(
            f"✅ لقب کاربر {user_link(msg.reply_to_message.from_user)} به «{title}» تغییر یافت.",
            parse_mode=ParseMode.HTML,
        )
    except (BadRequest, Forbidden) as e:
        await msg.reply_text(f"{MSG['bot_no_perm']}\n{str(e)[:80]}")


# ─────────────────────────── Registration ───────────────────────────
ENGLISH_CMDS = {
    "config": config_cmd,
    "promote": promote_cmd,
    "demote": demote_cmd,
    "modlist": modlist_cmd,
    "cleanmodlist": cleanmodlist_cmd,
    "adminlist": adminlist_cmd,
    "settitle": settitle_cmd,
}
PERSIAN_CMDS = {
    "پیکربندی": config_cmd,
    "پیکربندی مدیر": config_cmd,
    "تنظیمات مدیران": config_cmd,
    "مدیر": promote_cmd,
    "مدیر کن": promote_cmd,
    "ادمین کن": promote_cmd,
    "تنظیم مدیر": promote_cmd,
    "افزودن ادمین": addadmin_cmd,
    "ادمین جدید": addadmin_cmd,
    "حذف مدیر": demote_cmd,
    "حذف ادمین": rmadmin_cmd,
    "عزل": demote_cmd,
    "عزل کن": demote_cmd,
    "برکنار": demote_cmd,
    "لیست مدیران": modlist_cmd,
    "مدیران": modlist_cmd,
    "ادمینا": modlist_cmd,
    "ادمین‌ها": modlist_cmd,
    "پاکسازی لیست مدیران": cleanmodlist_cmd,
    "لیست ادمین ها": adminlist_cmd,
    "لیست ادمین": adminlist_cmd,
    "ادمین‌های ربات": adminlist_cmd,
    "تنظیم لقب": settitle_cmd,
    "لقب": settitle_cmd,
    "تنظیم عنوان": settitle_cmd,
}


def register(app) -> None:
    register_mixed(app, ENGLISH_CMDS, PERSIAN_CMDS)
