"""Anti-link handler — main logic is in listener.py + locks.py."""
from __future__ import annotations

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

from bot import db
from bot.decorators import admin_only
from bot.persian_router import register_mixed


@admin_only
async def antilink_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    args = (update.message.text or "").split()
    chat_id = update.effective_chat.id
    if len(args) < 2:
        cur = await db.get_setting(chat_id, "antilink", False)
        state = "فعال" if cur else "غیرفعال"
        wl = await db.get_whitelisted_links(chat_id)
        wl_text = "\n".join(f"• {w}" for w in wl) if wl else "خالی"
        await update.message.reply_text(
            f"🔗 ضد لینک: {state}\n\n"
            f"لینک‌های مجاز:\n{wl_text}\n\n"
            f"دستورات:\n"
            f"• <code>antilink on/off</code>\n"
            f"• <code>addlink example.com</code>\n"
            f"• <code>rmlink example.com</code>",
            parse_mode=ParseMode.HTML,
        )
        return
    state = args[1].lower() in ("on", "روشن", "enable", "1")
    await db.set_setting(chat_id, "antilink", state)
    if state:
        await db.add_lock(chat_id, "link")
    else:
        await db.remove_lock(chat_id, "link")
    await update.message.reply_text(f"✅ ضد لینک {'فعال' if state else 'غیرفعال'} شد.")


@admin_only
async def addlink_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("❌ استفاده: <code>addlink domain.com</code>", parse_mode=ParseMode.HTML)
        return
    await db.add_whitelisted_link(update.effective_chat.id, args[1])
    await update.message.reply_text(f"✅ لینک {args[1]} به لیست مجاز اضافه شد.")


@admin_only
async def rmlink_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("❌ استفاده: <code>rmlink domain.com</code>", parse_mode=ParseMode.HTML)
        return
    await db.remove_whitelisted_link(update.effective_chat.id, args[1])
    await update.message.reply_text(f"✅ لینک {args[1]} از لیست مجاز حذف شد.")


def register(app) -> None:
    register_mixed(
        app,
        {
            "antilink": antilink_cmd,
            "addlink": addlink_cmd,
            "rmlink": rmlink_cmd,
        },
        {
            "ضد لینک": antilink_cmd,
            "آنتی لینک": antilink_cmd,
            "لیست لینک مجاز": antilink_cmd,
            "ضد لینک روشن": antilink_cmd,
            "ضد لینک خاموش": antilink_cmd,
            "افزودن لینک مجاز": addlink_cmd,
            "لینک مجاز": addlink_cmd,
            "اجازه لینک": addlink_cmd,
            "حذف لینک مجاز": rmlink_cmd,
            "پاک کردن لینک مجاز": rmlink_cmd,
        },
    )
