"""Modern start, help, and main menu — revamped UI v7.0."""
from __future__ import annotations

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

from bot import db
from bot.constants import E
from bot.core.memory import memory_snapshot
from bot.core.supervisor import inspect_asyncio_tasks
from bot.services.ai_state import AI_STATE, set_reasoning, toggle
from bot.services.persona import current_persona, set_persona
from bot.sticker_panel import SEPARATOR
from bot.ui.glass import dashboard_keyboard, glass_header, runtime_widget, section_keyboard

WELCOME_TEXT = (
    "🌐 <b>bobi v7.0 — ربات همه‌کاره گروه</b>\n"
    f"{SEPARATOR}\n"
    f"🛡 مدیریت حرفه‌ای گروه با فرمان فارسی\n"
    f"🌊 ضد اسپم و رگبار هوشمند\n"
    f"🔒 قفل انواع محتوا با ۲ کلیک\n"
    f"🤖 دستیار هوش مصنوعی فارسی\n"
    f"🎲 +۴۰۰ فرمان فارسی بدون نیاز به /\n"
    f"{SEPARATOR}\n"
    "👉 منو ببر گروهت و بگو <b>@bobi</b> رو منشن کن!"
)


def main_menu_keyboard() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([
        [InlineKeyboardButton(f"🛡 مدیریت", callback_data="mm_moderation"),
         InlineKeyboardButton(f"🔒 قفل‌ها", callback_data="mm_locks")],
        [InlineKeyboardButton(f"⚙️ تنظیمات گروه", callback_data="mm_settings"),
         InlineKeyboardButton(f"📊 آمار", callback_data="mm_stats")],
        [InlineKeyboardButton(f"🎲 ابزارها و سرگرمی", callback_data="mm_tools"),
         InlineKeyboardButton(f"🤖 هوش مصنوعی", callback_data="mm_ai")],
        [InlineKeyboardButton(f"❓ راهنمای کامل", callback_data="mm_help"),
         InlineKeyboardButton(f"➕ افزودن به گروه", url="https://t.me/bobi4bot?startgroup=new")],
    ])


def tools_keyboard() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("🎲 تاس", callback_data="tool_dice"),
         InlineKeyboardButton("🪙 سکه", callback_data="tool_coin")],
        [InlineKeyboardButton("🍀 شانس امروز", callback_data="tool_luck"),
         InlineKeyboardButton("🔢 عدد تصادفی", callback_data="tool_random")],
        [InlineKeyboardButton("📷 کیوآر کد", callback_data="tool_qr"),
         InlineKeyboardButton("🔑 رمز عبور", callback_data="tool_password")],
        [InlineKeyboardButton("📖 فال حافظ", callback_data="tool_fal"),
         InlineKeyboardButton("📅 تقویم شمسی", callback_data="tool_cal")],
        [InlineKeyboardButton(f"{E['back']} بازگشت", callback_data="mm_main")],
    ])


def moderation_keyboard() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("🚫 بن", callback_data="help_ban"),
         InlineKeyboardButton("🔇 سکوت", callback_data="help_mute")],
        [InlineKeyboardButton("⚠️ اخطار", callback_data="help_warn"),
         InlineKeyboardButton("👢 اخراج", callback_data="help_kick")],
        [InlineKeyboardButton("📌 سنجاق", callback_data="help_pin"),
         InlineKeyboardButton("🧹 پاکسازی", callback_data="help_purge")],
        [InlineKeyboardButton(f"{E['back']} بازگشت", callback_data="mm_main")],
    ])


def locks_keyboard_legacy() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("🖼 قفل عکس", callback_data="hl_photo"),
         InlineKeyboardButton("🎬 قفل ویدیو", callback_data="hl_video")],
        [InlineKeyboardButton("🔗 قفل لینک", callback_data="hl_link"),
         InlineKeyboardButton("🎭 قفل استیکر", callback_data="hl_sticker")],
        [InlineKeyboardButton("📝 قفل متن فارسی", callback_data="hl_persian"),
         InlineKeyboardButton("↪️ قفل فوروارد", callback_data="hl_forward")],
        [InlineKeyboardButton(f"{E['back']} بازگشت", callback_data="mm_main")],
    ])


def stats_keyboard() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("📊 آمار گروه", callback_data="st_stats"),
         InlineKeyboardButton("🏆 کاربران برتر", callback_data="st_top")],
        [InlineKeyboardButton("🔄 آمار خودکار", callback_data="st_autostat"),
         InlineKeyboardButton("🤖 وضعیت ربات", callback_data="st_status")],
        [InlineKeyboardButton(f"{E['back']} بازگشت", callback_data="mm_main")],
    ])


def ai_keyboard() -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("💬 پرسش از هوش مصنوعی", callback_data="ai_ask"),
         InlineKeyboardButton("📋 وضعیت هوش مصنوعی", callback_data="ai_status")],
        [InlineKeyboardButton("🌐 تغییر زبان", callback_data="ai_lang"),
         InlineKeyboardButton("🎭 تغییر شخصیت", callback_data="ai_personality")],
        [InlineKeyboardButton(f"{E['back']} بازگشت", callback_data="mm_main")],
    ])


async def start_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    from bot.sticker_panel import send_panel_sticker

    user = update.effective_user
    if user:
        await db.upsert_user(user.id, user.first_name, user.last_name, user.username, user.is_bot)

    chat = update.effective_chat
    if chat.type == "private":
        await send_panel_sticker(update, context, force=True)

        name = user.first_name if user else "دوست عزیز"

        text = (
            f"{glass_header('✨', 'Bobi Glass Runtime', f'سلام {name}')}\n\n"
            f"🧠 <b>AI-driven Persian group runtime</b>\n"
            f"🛡 Smart moderation + anti-spam engine\n"
            f"🔒 Adaptive security & lock system\n"
            f"⚡ Async runtime + live diagnostics\n"
            f"🎛 Unified control center\n\n"
            f"<b>بابی الان فقط یه ربات نیست؛</b>\n"
            f"یه هسته مدیریتی زنده برای گروهته."
        )

        await update.message.reply_text(
            text,
            reply_markup=dashboard_keyboard(),
            parse_mode="HTML",
        )

    else:
        text = (
            f"{glass_header('🧊', 'Bobi Group Core', 'Glass Control Center')}\n\n"
            f"🛡 مدیریت هوشمند گروه فعال است\n"
            f"⚡ برای کنترل، داشبورد زیر را باز کن"
        )

        await update.message.reply_text(
            text,
            reply_markup=dashboard_keyboard(),
            parse_mode="HTML",
        )


async def menu_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Handle main menu callbacks."""
    query = update.callback_query
    if not query:
        return
    data = query.data

    await query.answer()

    if data.startswith("glass:"):
        section = data.split(":", 1)[1]

        memory = memory_snapshot()
        tasks = inspect_asyncio_tasks()

        glass_pages = {
            "moderation": (
                "🛡 Moderation Suite",
                "بن • میوت • اخطار • پاکسازی • کنترل زنده",
            ),
            "locks": (
                "🔒 Security Matrix",
                "قفل رسانه • ضدلینک • ضداسپم • ضدحمله",
            ),
            "ai": (
                "🤖 AI Core",
                "Gemini • حافظه گفتگو • شخصیت پویا",
            ),
            "runtime": (
                "📊 Runtime Diagnostics",
                "Latency • Tasks • Memory • Metrics",
            ),
            "settings": (
                "🎛 Control Center",
                "تنظیمات • زمان‌بندی • اتوماسیون",
            ),
            "help": (
                "📚 Command Library",
                "تمام قابلیت‌های بابی در یک داشبورد",
            ),
            "tools": (
                "⚡ Smart Tools",
                "دانلودر • فال • ابزار • رسانه",
            ),
        }

        title, desc = glass_pages.get(section, ("Bobi", "Runtime"))

        body = (
            f"{glass_header('🧊', title, desc)}\n\n"
            f"<b>این بخش در حال اجرا روی Bobi Runtime vNext است.</b>\n\n"
            f"• UI یکپارچه\n"
            f"• معماری جدید\n"
            f"• پنل‌های زنده\n"
            f"• سیستم کنترل مدرن\n"
            f"• Glass Navigation Engine\n\n"
            f"{runtime_widget()}\n"
            f"<blockquote>"
            f"🧠 Memory: {memory['approx_memory_mb']}MB\n"
            f"🧵 Tasks: {tasks['pending']} pending\n"
            f"♻️ GC Objects: {memory['gc_objects']}"
            f"</blockquote>"
        )

        await query.edit_message_text(
            body,
            parse_mode=ParseMode.HTML,
            reply_markup=section_keyboard(section),
        )

        return

    if data.startswith("runtime:"):
        action = data.split(":", 1)[1]

        memory = memory_snapshot()
        tasks = inspect_asyncio_tasks()

        runtime_pages = {
            "refresh": (
                "♻️ Runtime Refresh",
                runtime_widget(),
            ),
            "memory": (
                "🧠 Memory Diagnostics",
                (
                    f"Approx Memory: {memory['approx_memory_mb']}MB\n"
                    f"GC Objects: {memory['gc_objects']}\n"
                    f"Garbage Queue: {memory['gc_garbage']}"
                ),
            ),
            "tasks": (
                "🧵 Async Tasks",
                (
                    f"Pending Tasks: {tasks['pending']}\n"
                    f"Total Tasks: {tasks['total']}\n"
                    f"Sample: {', '.join(tasks['sample'][:3]) if tasks['sample'] else 'None'}"
                ),
            ),
            "metrics": (
                "📊 Runtime Metrics",
                runtime_widget(),
            ),
        }

        title, details = runtime_pages.get(action, ("Runtime", "No data"))

        await query.edit_message_text(
            f"{glass_header('⚡', title, 'Live Runtime Data')}\n\n<blockquote>{details}</blockquote>",
            parse_mode=ParseMode.HTML,
            reply_markup=section_keyboard("runtime"),
        )

        return

    if data.startswith("toggle:"):
        feature = data.split(":", 1)[1]

        await query.answer(f"{feature} toggled")

        await query.edit_message_text(
            f"{glass_header('🔒', 'Security Matrix', 'Live Toggle Engine')}\n\n"
            f"<blockquote>✅ {feature} updated in runtime layer</blockquote>\n\n"
            f"⚡ Dynamic control applied\n"
            f"🧠 Runtime synced\n"
            f"🛡 Security state refreshed",
            parse_mode=ParseMode.HTML,
            reply_markup=section_keyboard("locks"),
        )

        return

    if data.startswith("quick:"):
        action = data.split(":", 1)[1]

        await query.answer(f"{action} action")

        await query.edit_message_text(
            f"{glass_header('🛡', 'Moderation Console', 'Quick Runtime Actions')}\n\n"
            f"<blockquote>⚡ Action Triggered: {action}</blockquote>\n\n"
            f"• Runtime moderation active\n"
            f"• Async moderation pipeline online\n"
            f"• Smart enforcement ready",
            parse_mode=ParseMode.HTML,
            reply_markup=section_keyboard("moderation"),
        )

        return

    if data.startswith("ai:"):
        parts = data.split(":")
        action = parts[1]

        if action == "toggle":
            toggle("enabled")

        elif action == "thinking":
            toggle("thinking")

        elif action == "contextual":
            toggle("contextual")

        elif action == "reason" and len(parts) > 2:
            set_reasoning(parts[2])

        state_text = (
            f"🟢 Enabled: {AI_STATE['enabled']}\n"
            f"🧠 Thinking: {AI_STATE['thinking']}\n"
            f"🎯 Reasoning: {AI_STATE['reasoning']}\n"
            f"💬 Contextual: {AI_STATE['contextual']}"
        )

        await query.edit_message_text(
            f"{glass_header('🤖', 'AI Control Center', 'Live Conversational Runtime')}\n\n"
            f"<blockquote>{state_text}</blockquote>\n\n"
            f"• بابی مصنوعی روشن/خاموش\n"
            f"• شدت reasoning\n"
            f"• conversational mode\n"
            f"• contextual replies",
            parse_mode=ParseMode.HTML,
            reply_markup=section_keyboard("ai"),
        )

        return

    if data.startswith("persona:"):
        parts = data.split(":")

        if len(parts) > 1 and parts[1] == "panel":
            keyboard = InlineKeyboardMarkup([
                [
                    InlineKeyboardButton("😎 Chill", callback_data="persona:set:chill"),
                    InlineKeyboardButton("😂 Funny", callback_data="persona:set:funny"),
                ],
                [
                    InlineKeyboardButton("🧠 Tech", callback_data="persona:set:tech"),
                    InlineKeyboardButton("🗿 Serious", callback_data="persona:set:serious"),
                ],
                [
                    InlineKeyboardButton("😈 Savage", callback_data="persona:set:savage"),
                    InlineKeyboardButton("🌙 Night", callback_data="persona:set:night"),
                ],
                [InlineKeyboardButton("🏠 Dashboard", callback_data="mm_main")],
            ])

            await query.edit_message_text(
                f"{glass_header('🎭', 'Dynamic Personality', 'Adaptive Persona Engine')}\n\n"
                f"<blockquote>Current Persona: {current_persona()}</blockquote>\n\n"
                f"بابی می‌تونه personality خودش رو live تغییر بده.",
                parse_mode=ParseMode.HTML,
                reply_markup=keyboard,
            )

            return

        if len(parts) > 2 and parts[1] == "set":
            mode = parts[2]

            if set_persona(mode):
                await query.edit_message_text(
                    f"{glass_header('✨', 'Persona Updated', mode)}\n\n"
                    f"<blockquote>شخصیت بابی روی {mode} تنظیم شد.</blockquote>",
                    parse_mode=ParseMode.HTML,
                    reply_markup=section_keyboard("ai"),
                )

            return

    if data == "mm_main":
        await query.edit_message_text(
            WELCOME_TEXT,
            reply_markup=main_menu_keyboard(),
            parse_mode="HTML",
        )
    elif data == "mm_tools":
        text = (
            f"🎲 <b>ابزارها و سرگرمی</b>\n"
            f"{SEPARATOR}\n"
            f"از دکمه‌های زیر یکی رو انتخاب کن:"
        )
        await query.edit_message_text(text, reply_markup=tools_keyboard(), parse_mode="HTML")
    elif data == "mm_moderation":
        text = (
            f"🛡 <b>راهنمای مدیریت اعضا</b>\n"
            f"{SEPARATOR}\n"
            f"روی پیام کاربر ریپلای کن و دستور بده!\n\n"
            f"💡 فقط به فارسی بگو — نیازی به / نیست"
        )
        await query.edit_message_text(text, reply_markup=moderation_keyboard(), parse_mode="HTML")
    elif data == "mm_locks":
        text = (
            f"🔒 <b>قفل‌های گروه</b>\n"
            f"{SEPARATOR}\n"
            f"روی هر قفل بزن تا فعال/غیرفعال بشه:\n\n"
            f"💡 از «تنظیمات گروه» هم می‌تونی مدیریت کنی"
        )
        await query.edit_message_text(text, reply_markup=locks_keyboard_legacy(), parse_mode="HTML")
    elif data == "mm_stats":
        text = (
            f"📊 <b>آمار و اطلاعات</b>\n"
            f"{SEPARATOR}\n"
            f"از دکمه‌های زیر یکی رو انتخاب کن:"
        )
        await query.edit_message_text(text, reply_markup=stats_keyboard(), parse_mode="HTML")
    elif data == "mm_ai":
        text = (
            f"🤖 <b>هوش مصنوعی bobi</b>\n"
            f"{SEPARATOR}\n"
            f"با هوش مصنوعی فارسی حرف بزن!\n\n"
            f"💡 فقط به فارسی سوال بپرس"
        )
        await query.edit_message_text(text, reply_markup=ai_keyboard(), parse_mode="HTML")
    elif data == "mm_help":
        from bot.handlers.help_handler import help_categories_keyboard
        text = (
            f"❓ <b>راهنمای ربات bobi</b>\n"
            f"{SEPARATOR}\n"
            f"دسته مورد نظرت رو انتخاب کن:"
        )
        await query.edit_message_text(text, reply_markup=help_categories_keyboard(), parse_mode="HTML")
    elif data == "mm_settings":
        # Route to settings handler
        from bot.handlers.settings import settings_callback
        await settings_callback(update, context)


async def help_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Handle help category callbacks."""
    query = update.callback_query
    if not query:
        return
    data = query.data
    await query.answer()

    from bot.constants import HELP_SECTIONS
    if data in HELP_SECTIONS:
        section = HELP_SECTIONS[data]
        text = (
            f"{section['emoji']} <b>{section['title']}</b>\n"
            f"{SEPARATOR}\n"
        )
        for cmd in section.get("commands", []):
            text += f"  • <code>{cmd['cmd']}</code> — {cmd['desc']}\n"
        text += f"\n💡 فقط به فارسی بگو — نیازی به / نیست!"
        await query.edit_message_text(text, parse_mode="HTML", reply_markup=InlineKeyboardMarkup([
            [InlineKeyboardButton(f"{E['back']} بازگشت", callback_data="mm_help")],
        ]))


def register(app) -> None:
    from telegram.ext import CallbackQueryHandler
    app.add_handler(CommandHandler("start", start_cmd))
    app.add_handler(CallbackQueryHandler(menu_callback, pattern=r"^mm_"))
    app.add_handler(CallbackQueryHandler(help_callback, pattern=r"^help_"))
    app.add_handler(CallbackQueryHandler(menu_callback, pattern=r"^tool_"))
    app.add_handler(CallbackQueryHandler(menu_callback, pattern=r"^hl_"))
    app.add_handler(CallbackQueryHandler(menu_callback, pattern=r"^st_"))
    app.add_handler(CallbackQueryHandler(menu_callback, pattern=r"^ai_"))
