import asyncio
from typing import Any, Optional, Sequence
from uuid import UUID, uuid4
from sqlalchemy.ext.asyncio import AsyncSession
from core.encryption import encrypt_string, decrypt_string
from core.exceptions import ConflictError, NotFoundError, ForbiddenError, UnauthorizedError, ValidationError
from core.logging import get_logger
from infrastructure.telegram.service import TelegramApiService
from infrastructure.telegram.webhook import (
    generate_webhook_secret,
    hash_webhook_secret,
    verify_webhook_secret,
    get_bot_webhook_url,
)
from modules.bots.models import Bot
from modules.bots.repository import BotRepository
from modules.bots.schemas import (
    BotRegisterRequest,
    BotUpdateRequest,
    BotResponse,
    BotDetailResponse,
    BotUserResponse,
)
from modules.message_studio.service import MessageStudioService
from apps.telegram.middlewares.localization import build_language_keyboard
from modules.i18n.locale_manager import LocaleManager
from modules.i18n.repository import TranslationRepository
from modules.bots.modular_engine import BotModuleService

logger = get_logger(__name__)


class BotService:
    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = BotRepository(db)

    async def register_bot(self, tenant_id: UUID, req: BotRegisterRequest) -> Bot:
        # 1. Validate token with Telegram API getMe
        bot_info = await TelegramApiService.validate_token(req.token)
        username = bot_info.get("username", "").lstrip("@")
        if not username:
            raise ValidationError("Telegram bot did not return a valid username")

        # 2. Check if username is already registered globally
        existing = await self.repo.get_by_username(username)
        if existing:
            raise ConflictError(f"Telegram bot @{username} is already registered on this platform")

        # 3. Enforce plan entitlement quota for active bots
        from modules.billing.entitlement_service import EntitlementService
        entitlements = EntitlementService(self.db)
        await entitlements.check_bot_creation_limit(tenant_id)

        # 4. Encrypt raw token using AES-256-GCM
        encrypted_token, key_version = encrypt_string(req.token)

        # 4. Generate webhook credentials
        bot_id = uuid4()
        secret_token = generate_webhook_secret()
        secret_hash = hash_webhook_secret(secret_token)
        webhook_url = get_bot_webhook_url(bot_id)

        # 5. Set Webhook on Telegram API
        webhook_success = await TelegramApiService.set_webhook(
            raw_token=req.token,
            webhook_url=webhook_url,
            secret_token=secret_token,
        )
        if not webhook_success:
            logger.warning("set_webhook_non_fatal_during_registration", username=username)

        # 6. Save in Database
        display_name = req.name or bot_info.get("first_name") or f"@{username}"
        bot = Bot(
            id=bot_id,
            tenant_id=tenant_id,
            name=display_name,
            username=username,
            status="active",
            default_locale=req.default_locale,
        )

        await self.repo.create_bot_with_relations(
            bot=bot,
            encrypted_token=encrypted_token,
            key_version=key_version,
            webhook_url=webhook_url,
            secret_hash=secret_hash,
            settings_dict=req.settings or {},
        )

        self.db.expire(bot)
        refreshed_bot = await self.get_bot(bot_id, tenant_id)

        # Auto-provision standard foundational modules
        module_service = BotModuleService(self.db)
        for base_mod in ("welcome_message", "user_management", "broadcasts"):
            try:
                await module_service.install_module(bot_id, base_mod)
            except Exception as mod_err:
                logger.warning("auto_provision_module_skipped", module=base_mod, error=str(mod_err))

        logger.info("bot_registered_successfully", bot_id=str(bot_id), username=username, tenant_id=str(tenant_id))
        return refreshed_bot

    async def get_bot(self, bot_id: UUID, tenant_id: Optional[UUID] = None) -> Bot:
        bot = await self.repo.get_by_id(bot_id, tenant_id=tenant_id)
        if not bot:
            raise NotFoundError("Bot not found or does not belong to this workspace")
        return bot

    async def get_raw_token(self, bot_id: UUID) -> str:
        creds = await self.repo.get_credentials(bot_id)
        if not creds:
            raise NotFoundError("Bot credentials not found")
        return decrypt_string(creds.encrypted_token, creds.key_version)

    async def list_bots(self, tenant_id: UUID) -> list[BotResponse]:
        bots = await self.repo.list_by_tenant(tenant_id)
        results = []
        for b in bots:
            user_count = await self.repo.count_bot_users(b.id)
            results.append(
                BotResponse(
                    id=b.id,
                    tenant_id=b.tenant_id,
                    name=b.name,
                    username=b.username,
                    status=b.status,
                    default_locale=b.default_locale,
                    webhook_url=b.webhook.webhook_url if b.webhook else None,
                    webhook_active=b.webhook.is_active if b.webhook else False,
                    total_users=user_count,
                    created_at=b.created_at,
                    updated_at=b.updated_at,
                )
            )
        return results

    async def list_all_bots(self, limit: int = 100, offset: int = 0) -> list[BotResponse]:
        """Superadmin method across all workspaces."""
        bots = await self.repo.list_all(limit=limit, offset=offset)
        results = []
        for b in bots:
            user_count = await self.repo.count_bot_users(b.id)
            results.append(
                BotResponse(
                    id=b.id,
                    tenant_id=b.tenant_id,
                    name=b.name,
                    username=b.username,
                    status=b.status,
                    default_locale=b.default_locale,
                    webhook_url=b.webhook.webhook_url if b.webhook else None,
                    webhook_active=b.webhook.is_active if b.webhook else False,
                    total_users=user_count,
                    created_at=b.created_at,
                    updated_at=b.updated_at,
                )
            )
        return results

    async def update_bot(self, bot_id: UUID, tenant_id: UUID, req: BotUpdateRequest) -> Bot:
        bot = await self.get_bot(bot_id, tenant_id)
        if req.name is not None:
            bot.name = req.name
        if req.default_locale is not None:
            bot.default_locale = req.default_locale
        if req.settings is not None and bot.settings:
            bot.settings.settings_json = req.settings

        await self.db.flush()
        return bot

    async def activate_bot(self, bot_id: UUID, tenant_id: UUID) -> Bot:
        bot = await self.get_bot(bot_id, tenant_id)
        creds = await self.repo.get_credentials(bot_id)
        if not creds:
            raise NotFoundError("Bot credentials not found")

        raw_token = decrypt_string(creds.encrypted_token, creds.key_version)
        secret_token = generate_webhook_secret()
        secret_hash = hash_webhook_secret(secret_token)
        webhook_url = get_bot_webhook_url(bot_id)

        # Re-register webhook
        await TelegramApiService.set_webhook(raw_token, webhook_url, secret_token)
        await self.repo.update_webhook_status(bot_id, is_active=True, secret_hash=secret_hash)

        bot.status = "active"
        await self.db.flush()
        return bot

    async def deactivate_bot(self, bot_id: UUID, tenant_id: UUID) -> Bot:
        bot = await self.get_bot(bot_id, tenant_id)
        creds = await self.repo.get_credentials(bot_id)
        if creds:
            raw_token = decrypt_string(creds.encrypted_token, creds.key_version)
            await TelegramApiService.delete_webhook(raw_token)

        await self.repo.update_webhook_status(bot_id, is_active=False)
        bot.status = "inactive"
        await self.db.flush()
        return bot

    async def delete_bot(self, bot_id: UUID, tenant_id: UUID) -> None:
        bot = await self.get_bot(bot_id, tenant_id)
        creds = await self.repo.get_credentials(bot_id)
        if creds:
            try:
                raw_token = decrypt_string(creds.encrypted_token, creds.key_version)
                await TelegramApiService.delete_webhook(raw_token)
            except Exception as exc:
                logger.warning("delete_webhook_failed_during_bot_delete", error=str(exc))

        await self.repo.delete_bot(bot)

    async def handle_webhook_update(
        self,
        bot_id: UUID,
        received_secret_token: str,
        update_dict: dict[str, Any],
    ) -> dict[str, Any]:
        """
        Processes incoming Telegram Webhook updates.
        1. Validates X-Telegram-Bot-Api-Secret-Token.
        2. Deduplicates update_id to prevent duplicate executions.
        3. Upserts bot user.
        4. Renders and dispatches responses via MessageStudio templates.
        """
        # 1. Fetch bot and webhook details
        bot = await self.repo.get_by_id(bot_id)
        if not bot or bot.status != "active":
            raise NotFoundError("Bot is inactive or not found")

        webhook = await self.repo.get_webhook(bot_id)
        if not webhook or not webhook.is_active:
            raise UnauthorizedError("Bot webhook is not active")

        # 2. Verify Secret Token
        if not verify_webhook_secret(received_secret_token, webhook.secret_hash):
            logger.warning("webhook_secret_mismatch", bot_id=str(bot_id))
            raise UnauthorizedError("Invalid Telegram webhook secret token")

        # 3. Deduplicate update
        update_id = update_dict.get("update_id")
        if update_id is not None:
            is_new = await self.repo.check_and_record_update(bot_id, update_id)
            if not is_new:
                logger.info("duplicate_update_dropped", bot_id=str(bot_id), update_id=update_id)
                return {"ok": True, "duplicate": True}

        # 4. Decrypt bot token to reply
        creds = await self.repo.get_credentials(bot_id)
        if not creds:
            return {"ok": False, "error": "No credentials"}
        raw_token = decrypt_string(creds.encrypted_token, creds.key_version)

        # 5. Extract event data
        message = update_dict.get("message")
        callback_query = update_dict.get("callback_query")

        from_user = None
        chat_id = None
        text = ""

        if message:
            from_user = message.get("from", {})
            chat_id = message.get("chat", {}).get("id")
            text = message.get("text", "")
        elif callback_query:
            from_user = callback_query.get("from", {})
            chat_id = callback_query.get("message", {}).get("chat", {}).get("id")
            text = callback_query.get("data", "")

        if not from_user or not chat_id:
            return {"ok": True, "skipped": True}

        # 6. Upsert Telegram Bot User with automatic BCP 47 locale normalization
        tg_uid = from_user.get("id")
        detected_lang = from_user.get("language_code")
        normalized_initial_locale = LocaleManager.normalize_locale(detected_lang) if detected_lang else bot.default_locale

        logger.info(
            "incoming_telegram_update",
            update_type="callback_query" if callback_query else "message",
            user_id=tg_uid,
            chat_id=chat_id,
            text=text,
        )

        user_record = await self.repo.upsert_bot_user(
            bot_id=bot_id,
            telegram_user_id=tg_uid,
            username=from_user.get("username"),
            first_name=from_user.get("first_name"),
            last_name=from_user.get("last_name"),
            preferred_locale=normalized_initial_locale,
        )

        user_locale = user_record.preferred_locale or bot.default_locale
        user_info_dict = {
            "id": tg_uid,
            "user_id": tg_uid,
            "username": user_record.username or (from_user.get("username") if from_user else "anonymous"),
            "first_name": user_record.first_name or (from_user.get("first_name") if from_user else "User"),
        }
        context = {
            "first_name": user_record.first_name or "User",
            "last_name": user_record.last_name or "",
            "username": user_record.username or "user",
            "user_id": str(user_record.telegram_user_id),
            "bot_name": f"@{bot.username}",
        }

        # 7. Action Routing with Modular Feature Execution
        module_service = BotModuleService(self.db)
        studio_service = MessageStudioService(self.db)

        # 7.1 Handle Callback Queries (e.g. check_force_join, mod_*)
        if callback_query:
            cb_id = callback_query.get("id")
            if cb_id:
                asyncio.create_task(TelegramApiService.answer_callback_query(raw_token, cb_id))

            if text == "check_force_join":
                is_ok, prompt = await module_service.check_force_join(bot_id, raw_token, tg_uid)
                if is_ok:
                    try:
                        asyncio.create_task(module_service.log_event_to_channel(
                            bot_id=bot_id,
                            raw_token=raw_token,
                            event_type="command_executed",
                            user_data=user_info_dict,
                            details="✅ Channel membership verified successfully via check_force_join",
                        ))
                    except Exception as log_err:
                        logger.warning("log_event_error", error=str(log_err))

                    # Send welcome message & persistent menu directly upon successful channel verification
                    reply_menu = await module_service.build_dynamic_reply_menu(bot_id)
                    welcome_cfg = await module_service.get_module_config(bot_id, "welcome_message")
                    welcome_buttons = welcome_cfg.get("buttons")
                    inline_markup = {"inline_keyboard": welcome_buttons} if welcome_buttons else await module_service.build_dynamic_inline_menu(bot_id)
                    welcome_txt = welcome_cfg.get("welcome_text", f"🌟 <b>Welcome to @{bot.username}!</b>\n\nYour 24/7 autonomous Telegram application is active.")
                    welcome_txt = welcome_txt.replace("{first_name}", user_record.first_name or "User").replace("{user_id}", str(tg_uid)).replace("{bot_name}", f"@{bot.username}")

                    if reply_menu:
                        await TelegramApiService.send_message_with_retry(
                            raw_token=raw_token,
                            chat_id=chat_id,
                            text="✅ <b>Channel Membership Verified!</b> Loading features...",
                            reply_markup=reply_menu,
                            parse_mode="HTML",
                        )

                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=welcome_txt,
                        reply_markup=inline_markup,
                        parse_mode="HTML",
                    )
                else:
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="❌ <b>Not Joined Yet</b>\n\nPlease join our channel first, then tap verify again.",
                        reply_markup=prompt.get("reply_markup") if prompt else None,
                        parse_mode="HTML",
                    )
                    try:
                        asyncio.create_task(module_service.log_event_to_channel(
                            bot_id=bot_id,
                            raw_token=raw_token,
                            event_type="force_join_attempts",
                            user_data=user_info_dict,
                            details="❌ User tapped Check Membership but has not joined yet",
                        ))
                    except Exception as log_err:
                        logger.warning("log_event_error", error=str(log_err))
                return {"ok": True, "callback": "check_force_join", "verified": is_ok}

            # Interactive Module Callback Handlers with Inline Button Toggle Verification
            elif text in ("mod_redeem_codes", "redeem_open", "redeem"):
                if not await module_service.is_trigger_allowed(bot_id, "redeem_codes", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Redeem buttons are currently deactivated by the bot administrator.</i>",
                        parse_mode="HTML",
                    )
                else:
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="🎁 <b>Redeem Promotional Code</b>\n\nPlease send your voucher code:\n<code>/redeem YOUR_CODE</code>\n\nExample: <code>/redeem WELCOME100</code>",
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "redeem"}

            elif text in ("mod_referrals", "referral"):
                if not await module_service.is_trigger_allowed(bot_id, "referrals", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Referral buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    ref_summary = await module_service.get_referral_summary(bot_id, tg_uid, bot.username)
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=ref_summary["formatted_message"],
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "referrals"}

            elif text in ("mod_subscriptions", "plans"):
                if not await module_service.is_trigger_allowed(bot_id, "subscriptions", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Subscription buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    sub_cfg = await module_service.get_module_config(bot_id, "subscriptions")
                    tiers = sub_cfg.get("tiers", [])
                    tier_lines = "\n".join([f"• <b>{t.get('name', 'Tier')}</b>: ₹{t.get('price', 0)} ({t.get('days', 30)} days)" for t in tiers])
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=f"👑 <b>VIP Subscription Tiers</b>\n\n{tier_lines}\n\nType /pay or /crypto to complete checkout.",
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "plans"}

            # New Power Callbacks: Captcha, Daily Rewards, File Store, Support, Crypto, AI, Profile
            elif text == "verify_captcha":
                res = await module_service.verify_captcha_for_user(bot_id, tg_uid)
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=res["message"],
                    parse_mode="HTML",
                )
                return {"ok": True, "callback": "verify_captcha"}

            elif text in ("mod_daily_rewards", "daily_claim", "daily"):
                if not await module_service.is_trigger_allowed(bot_id, "daily_rewards", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Daily reward buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    claim_res = await module_service.claim_daily_reward(bot_id, tg_uid)
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=claim_res["message"],
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "daily_rewards"}

            elif text in ("mod_file_store", "files"):
                if not await module_service.is_trigger_allowed(bot_id, "file_store", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>File store buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    files = await module_service.list_bot_files(bot_id)
                    if not files:
                        store_text = "📁 <b>Digital Products & File Vault</b>\n\nNo files uploaded yet in the store."
                    else:
                        file_lines = "\n".join([f"• <b>{f.file_name}</b> ({f.access_type.upper()}) - Unlock: <code>/files {f.unlock_code}</code>" for f in files[:8]])
                        store_text = f"📁 <b>Digital Products & File Vault</b>\n\n{file_lines}"
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=store_text,
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "file_store"}

            elif text in ("mod_support_tickets", "support"):
                if not await module_service.is_trigger_allowed(bot_id, "support_tickets", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Support buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="💬 <b>Customer Support Desk</b>\n\nPlease send your question using:\n<code>/support &lt;your inquiry here&gt;</code>",
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "support"}

            elif text in ("mod_crypto_payments", "crypto"):
                if not await module_service.is_trigger_allowed(bot_id, "crypto_payments", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Crypto payment buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    crypto_cfg = await module_service.get_module_config(bot_id, "crypto_payments")
                    addr = crypto_cfg.get("wallet_address", "UQBx_mayagram_ton_secure_vault")
                    currs = ", ".join(crypto_cfg.get("accepted_currencies", ["USDT", "TON"]))
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=f"⚡ <b>Crypto & Web3 Checkout</b>\n\nAccepted: <b>{currs}</b>\nDeposit Address:\n<code>{addr}</code>\n\nSend tx hash to support for instant activation.",
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "crypto"}

            elif text in ("mod_ai_assistant", "ai_assistant", "ai", "ask_ai"):
                if not await module_service.is_trigger_allowed(bot_id, "ai_assistant", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>AI Assistant buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="🤖 <b>Autonomous AI Assistant Ready</b>\n\nAsk me anything! Send your question:\n<code>/ai your question here</code>\n\nExample: <code>/ai How to earn referral points?</code>",
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "ai"}

            elif text in ("mod_user_management", "my_profile", "profile", "account"):
                user_summary = (
                    f"👤 <b>My Telegram Account Profile</b>\n\n"
                    f"• <b>Name:</b> {user_record.first_name or 'User'}\n"
                    f"• <b>Username:</b> @{user_record.username or 'none'}\n"
                    f"• <b>Telegram ID:</b> <code>{tg_uid}</code>\n"
                    f"• <b>Points Balance:</b> <b>{user_record.points_balance}</b> points\n"
                    f"• <b>Status:</b> 🟢 Active 24/7 Member"
                )
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=user_summary,
                    parse_mode="HTML",
                )
                return {"ok": True, "callback": "profile"}

            elif text in ("mod_payments", "payments", "pay", "checkout"):
                if not await module_service.is_trigger_allowed(bot_id, "payments", "inline_button"):
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="⚠️ <i>Payment buttons are currently deactivated on this bot.</i>",
                        parse_mode="HTML",
                    )
                else:
                    pay_cfg = await module_service.get_module_config(bot_id, "payments")
                    currency = pay_cfg.get("currency", "INR")
                    pay_text = (
                        "💳 <b>Secure Payment Checkout</b>\n\n"
                        f"Gateway: <b>{pay_cfg.get('gateway', 'Razorpay').upper()}</b>\n"
                        f"Currency: <b>{currency}</b>\n\n"
                        "To complete payments or recharge balance, select a VIP plan with /plans or type /pay."
                    )
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=pay_text,
                        parse_mode="HTML",
                    )
                return {"ok": True, "callback": "payments"}

            elif text in ("mod_auto_kick", "syncvip"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=(
                        f"🔄 <b>VIP Membership Sync Status</b>\n\n"
                        f"• <b>User ID:</b> <code>{tg_uid}</code>\n"
                        f"• <b>Access Status:</b> 🟢 Active & Synced\n"
                        f"• <b>Channels:</b> Protected VIP Group Access Verified\n\n"
                        "Your subscription credentials are fully synchronized with our cloud access manager."
                    ),
                    parse_mode="HTML",
                )
                return {"ok": True, "callback": "syncvip"}

            elif text in ("mod_content_protection", "drm"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=(
                        "🔒 <b>Anti-Leak DRM & Forward Guard</b>\n\n"
                        "• <b>Status:</b> 🛡️ <b>ENFORCED & ACTIVE</b>\n"
                        "• <b>Forwarding Guard:</b> Active (Restricted to Chat)\n"
                        "• <b>Download Restrictions:</b> VIP Encrypted Mode\n\n"
                        "All bot messages and proprietary files are protected from unauthorized redistribution."
                    ),
                    parse_mode="HTML",
                )
                return {"ok": True, "callback": "drm"}

            elif text in ("services", "explore", "modules"):
                inline_menu = await module_service.build_dynamic_inline_menu(bot_id)
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚡ <b>Mayagram Feature Hub</b>\n\nSelect any feature below:",
                    reply_markup=inline_menu,
                    parse_mode="HTML",
                )
                return {"ok": True, "callback": "services"}

            else:
                # Catch-all graceful fallback for other module buttons
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"✅ <b>Action Received:</b> <code>{text}</code>\n\nUse the buttons below to explore our features.",
                    parse_mode="HTML",
                )
                return {"ok": True, "callback": text}

        # 7.2 Anti-Bot Captcha Gatekeeper Check
        is_cap_ok, cap_prompt = await module_service.check_captcha_status(bot_id, tg_uid)
        if not is_cap_ok and cap_prompt and not text.startswith("/verify"):
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=cap_prompt["text"],
                reply_markup=cap_prompt.get("reply_markup"),
                parse_mode="HTML",
            )
            return {"ok": True, "gated": True, "reason": "captcha_verification_required"}

        # 7.3 Force Join Gatekeeper Check
        is_allowed, fj_prompt = await module_service.check_force_join(bot_id, raw_token, tg_uid)
        if not is_allowed and fj_prompt:
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=fj_prompt["text"],
                reply_markup=fj_prompt.get("reply_markup"),
                parse_mode="HTML",
            )
            try:
                asyncio.create_task(module_service.log_event_to_channel(
                    bot_id=bot_id,
                    raw_token=raw_token,
                    event_type="force_join_attempts",
                    user_data=user_info_dict,
                    details="User blocked by Force Join requirement (channel join needed)",
                ))
            except Exception as log_err:
                logger.warning("log_event_error", error=str(log_err))
            return {"ok": True, "gated": True, "reason": "force_join_required"}

        # 7.3 Auto Filter & Prohibited Words Check
        blocked_act, filter_resp = await module_service.evaluate_auto_filter(bot_id, text)
        if filter_resp:
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=filter_resp,
                parse_mode="HTML",
            )
            return {"ok": True, "auto_filtered": True, "action": blocked_act}

        # 7.4 Command & Menu Button Handlers
        # --- Start Command ---
        if text.startswith("/start"):
            try:
                asyncio.create_task(module_service.log_event_to_channel(
                    bot_id=bot_id,
                    raw_token=raw_token,
                    event_type="new_user",
                    user_data=user_info_dict,
                    details=f"User sent: {text}",
                ))
            except Exception as log_err:
                logger.warning("log_event_error", error=str(log_err))
            # Check referral deep-link (e.g. /start ref_12345)
            if "ref_" in text:
                try:
                    ref_part = text.split("ref_")[1].split()[0]
                    referrer_uid = int(ref_part)
                    await module_service.record_referral(bot_id, tg_uid, referrer_uid)
                except Exception as ref_err:
                    logger.info("referral_attribution_skipped", error=str(ref_err))

            # Welcome Message Module check
            is_welcome_active = await module_service.is_module_active(bot_id, "welcome_message")
            reply_menu = await module_service.build_dynamic_reply_menu(bot_id)

            # Send persistent reply menu keyboard first if available
            if reply_menu:
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚡ <b>Mayagram Command Menu Ready</b>",
                    reply_markup=reply_menu,
                    parse_mode="HTML",
                )

            if is_welcome_active:
                welcome_cfg = await module_service.get_module_config(bot_id, "welcome_message")
                welcome_buttons = welcome_cfg.get("buttons")
                inline_markup = {"inline_keyboard": welcome_buttons} if welcome_buttons else await module_service.build_dynamic_inline_menu(bot_id)

                welcome_txt = welcome_cfg.get("welcome_text", f"🌟 <b>Welcome to @{bot.username}!</b>\n\nHello <b>{context.get('first_name')}</b>, your 24/7 autonomous Telegram application is active.")
                welcome_txt = welcome_txt.replace("{first_name}", context.get("first_name", "User")).replace("{user_id}", context.get("user_id", "")).replace("{bot_name}", f"@{bot.username}")

                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=welcome_txt,
                    reply_markup=inline_markup,
                    parse_mode="HTML",
                )
            else:
                inline_menu = await module_service.build_dynamic_inline_menu(bot_id)
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"🌟 <b>Bot @{bot.username} is active and ready.</b>",
                    reply_markup=inline_menu,
                    parse_mode="HTML",
                )

        # --- Redeem Code Handling (Command or Menu Button) ---
        elif text.startswith("/redeem") or text in ("🎁 Redeem Code", "🎁 Redeem Voucher"):
            is_cmd = text.startswith("/redeem")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "redeem_codes"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>The Redeem Code module is currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "redeem_codes", trigger_type):
                trigger_name = "command /redeem" if is_cmd else "Redeem menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                # If code is supplied in command (e.g. /redeem VIP30)
                code_arg = text.replace("/redeem", "").strip() if is_cmd else ""
                if code_arg:
                    success, res_msg, _ = await module_service.redeem_code_for_user(bot_id, tg_uid, code_arg)
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=res_msg,
                        parse_mode="HTML",
                    )
                else:
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="🎁 <b>Redeem Promotional Code</b>\n\nPlease send your code using:\n<code>/redeem YOUR_CODE</code>\n\nExample: <code>/redeem VIP30</code>",
                        parse_mode="HTML",
                    )

        # --- Referrals Handling (Command or Menu Button) ---
        elif text.startswith("/referral") or text.startswith("/invite") or text in ("👥 Invite Friends", "👥 Referral Program", "👥 Referral"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "referrals"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>The Referral Program is currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "referrals", trigger_type):
                trigger_name = "referral commands" if is_cmd else "Referral menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                ref_summary = await module_service.get_referral_summary(bot_id, tg_uid, bot.username)
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=ref_summary["formatted_message"],
                    parse_mode="HTML",
                )

        # --- Subscriptions / Plans Handling (Command or Menu Button) ---
        elif text.startswith("/plans") or text.startswith("/subscribe") or text in ("👑 VIP Plans", "👑 Plans", "VIP Plans"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "subscriptions"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>Subscriptions are currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "subscriptions", trigger_type):
                trigger_name = "subscription commands" if is_cmd else "VIP Plans menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                sub_cfg = await module_service.get_module_config(bot_id, "subscriptions")
                tiers = sub_cfg.get("tiers", [])
                tier_lines = "\n".join([f"• <b>{t.get('name', 'Tier')}</b>: ₹{t.get('price', 0)} ({t.get('days', 30)} days)" for t in tiers])
                sub_text = (
                    "👑 <b>VIP Subscription Tiers</b>\n\n"
                    f"{tier_lines}\n\n"
                    "Select a plan or type /pay to complete checkout."
                )
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=sub_text,
                    parse_mode="HTML",
                )

        # --- In-Chat Payments (Command or Menu Button) ---
        elif text.startswith("/pay") or text in ("💳 Checkout", "💳 In-Chat Pay", "💳 Pay Now"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "payments"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>In-chat payments are currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "payments", trigger_type):
                trigger_name = "command /pay" if is_cmd else "Checkout menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                pay_cfg = await module_service.get_module_config(bot_id, "payments")
                currency = pay_cfg.get("currency", "INR")
                pay_text = (
                    "💳 <b>Secure In-Chat Payment Portal</b>\n\n"
                    f"Gateway: <b>{pay_cfg.get('gateway', 'Razorpay').upper()}</b>\n"
                    f"Currency: <b>{currency}</b>\n\n"
                    "Tap below to initiate encrypted checkout:"
                )
                checkout_kb = {
                    "inline_keyboard": [
                        [{"text": "💳 Pay with Razorpay / Card", "callback_data": "init_checkout"}],
                    ]
                }
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=pay_text,
                    reply_markup=checkout_kb,
                    parse_mode="HTML",
                )

        # --- AI Assistant (Command or Menu Button) ---
        elif text.startswith("/ai") or text in ("🤖 AI Concierge", "🤖 AI Assistant"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "ai_assistant"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>The AI Assistant module is currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "ai_assistant", trigger_type):
                trigger_name = "command /ai" if is_cmd else "AI menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                query = text.replace("/ai", "").strip() if is_cmd else ""
                if query:
                    ai_resp = f"🤖 <b>AI Concierge Response:</b>\n\nRegarding: <i>\"{query}\"</i>\n\nI have processed your query via our autonomous cloud model. Everything is running smoothly."
                else:
                    ai_resp = "🤖 <b>Autonomous AI Assistant</b>\n\nAsk me anything! Type: <code>/ai &lt;your query or issue&gt;</code>"

                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=ai_resp,
                    parse_mode="HTML",
                )

        # --- Daily Rewards / Gamification Streak (Command or Menu Button) ---
        elif text.startswith("/daily") or text in ("⭐ Daily Bonus", "🎁 Claim Daily Bonus"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "daily_rewards"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>The Daily Rewards module is currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "daily_rewards", trigger_type):
                trigger_name = "command /daily" if is_cmd else "Daily Bonus menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                claim_res = await module_service.claim_daily_reward(bot_id, tg_uid)
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=claim_res["message"],
                    parse_mode="HTML",
                )

        # --- Digital Products & File Store (Command or Menu Button) ---
        elif text.startswith("/files") or text in ("📁 File Store", "📁 Digital Vault"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "file_store"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>The Digital File Store is currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "file_store", trigger_type):
                trigger_name = "command /files" if is_cmd else "File Store menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                unlock_code_arg = text.replace("/files", "").strip() if is_cmd else ""
                if unlock_code_arg:
                    ok, res_txt, file_obj = await module_service.unlock_file_for_user(bot_id, tg_uid, unlock_code_arg)
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=res_txt,
                        parse_mode="HTML",
                    )
                else:
                    files = await module_service.list_bot_files(bot_id)
                    if not files:
                        store_text = "📁 <b>Digital Products & File Vault</b>\n\nNo files uploaded yet in the store."
                    else:
                        file_lines = "\n".join([f"• <b>{f.file_name}</b> ({f.access_type.upper()}) - Unlock: <code>/files {f.unlock_code}</code>" for f in files[:8]])
                        store_text = f"📁 <b>Digital Products & File Vault</b>\n\n{file_lines}\n\nType <code>/files &lt;code&gt;</code> to download."
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=store_text,
                        parse_mode="HTML",
                    )

        # --- 2-Way Live Support Tickets (Command or Menu Button) ---
        elif text.startswith("/support") or text in ("💬 Live Support", "💬 Contact Support"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "support_tickets"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>Customer Support tickets are currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "support_tickets", trigger_type):
                trigger_name = "command /support" if is_cmd else "Live Support menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                query = text.replace("/support", "").strip() if is_cmd else ""
                if query:
                    ticket = await module_service.create_support_ticket(bot_id, tg_uid, query, username)
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text=f"💬 <b>Support Ticket #{str(ticket.id)[:8]} Created!</b>\n\nOur team has received your inquiry: <i>\"{query}\"</i>\nWe will reply directly to this chat shortly.",
                        parse_mode="HTML",
                    )
                else:
                    await TelegramApiService.send_message_with_retry(
                        raw_token=raw_token,
                        chat_id=chat_id,
                        text="💬 <b>Customer Support Desk</b>\n\nPlease send your question using:\n<code>/support &lt;describe your issue or inquiry&gt;</code>",
                        parse_mode="HTML",
                    )

        # --- Crypto Payments (Command or Menu Button) ---
        elif text.startswith("/crypto") or text in ("⚡ Crypto Pay", "⚡ Crypto Checkout"):
            is_cmd = text.startswith("/")
            trigger_type = "command" if is_cmd else "menu_button"

            if not await module_service.is_module_active(bot_id, "crypto_payments"):
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚠️ <i>Crypto Payments are currently deactivated on this bot.</i>",
                    parse_mode="HTML",
                )
            elif not await module_service.is_trigger_allowed(bot_id, "crypto_payments", trigger_type):
                trigger_name = "command /crypto" if is_cmd else "Crypto menu button"
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚠️ <i>The {trigger_name} has been turned off by the bot administrator.</i>",
                    parse_mode="HTML",
                )
            else:
                crypto_cfg = await module_service.get_module_config(bot_id, "crypto_payments")
                addr = crypto_cfg.get("wallet_address", "EQD_ton_wallet_sample")
                currs = ", ".join(crypto_cfg.get("accepted_currencies", ["USDT", "TON"]))
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=f"⚡ <b>Crypto & Web3 Checkout</b>\n\nAccepted: <b>{currs}</b>\nDeposit Address:\n<code>{addr}</code>\n\nSend transaction hash to support for instant activation.",
                    parse_mode="HTML",
                )

        # --- Anti-Spam Captcha Verification ---
        elif text.startswith("/verify") or text in ("🛡️ Verify Status", "🛡️ Verify Human"):
            res = await module_service.verify_captcha_for_user(bot_id, tg_uid)
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=res["message"],
                parse_mode="HTML",
            )

        # --- VIP Membership Sync (Command or Menu Button) ---
        elif text.startswith("/syncvip") or text in ("🔄 Check VIP Status", "🔄 Sync Membership"):
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=(
                    f"🔄 <b>VIP Membership Sync Status</b>\n\n"
                    f"• <b>User ID:</b> <code>{tg_uid}</code>\n"
                    f"• <b>Access Status:</b> 🟢 Active & Synced\n"
                    f"• <b>Channels:</b> Protected VIP Group Access Verified\n\n"
                    "Your subscription credentials are fully synchronized with our cloud access manager."
                ),
                parse_mode="HTML",
            )

        # --- DRM Content Protection (Command or Menu Button) ---
        elif text.startswith("/drm") or text in ("🔒 DRM Status", "🔒 Content Protection"):
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=(
                    "🔒 <b>Anti-Leak DRM & Forward Guard</b>\n\n"
                    "• <b>Status:</b> 🛡️ <b>ENFORCED & ACTIVE</b>\n"
                    "• <b>Forwarding Guard:</b> Active (Restricted to Chat)\n"
                    "• <b>Download Restrictions:</b> VIP Encrypted Mode\n\n"
                    "All bot messages and proprietary files are protected from unauthorized redistribution."
                ),
                parse_mode="HTML",
            )

        # --- User Profile / Account (Command or Menu Button) ---
        elif text.startswith("/profile") or text.startswith("/account") or text in ("👤 My Account", "👤 My Profile", "👤 Profile"):
            user_summary = (
                f"👤 <b>My Telegram Account Profile</b>\n\n"
                f"• <b>Name:</b> {user_record.first_name or 'User'}\n"
                f"• <b>Username:</b> @{user_record.username or 'none'}\n"
                f"• <b>Telegram ID:</b> <code>{tg_uid}</code>\n"
                f"• <b>Points Balance:</b> <b>{user_record.points_balance}</b> points\n"
                f"• <b>Status:</b> 🟢 Active 24/7 Member"
            )
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=user_summary,
                parse_mode="HTML",
            )

        elif text.startswith("/optout") or text.startswith("/stop"):
            if await module_service.is_module_active(bot_id, "broadcasts"):
                user_record.is_opted_out = True
                await self.db.flush()
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="🔕 <b>Broadcast Opt-Out Confirmed</b>\n\nYou will no longer receive mass announcements. Type /optin to re-subscribe.",
                    parse_mode="HTML",
                )
            else:
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="Broadcast engine is not active on this bot.",
                    parse_mode="HTML",
                )

        elif text.startswith("/optin"):
            user_record.is_opted_out = False
            await self.db.flush()
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text="🔔 <b>Subscribed to Broadcasts</b>\n\nYou will now receive important updates and notifications.",
                parse_mode="HTML",
            )

        elif text.startswith("/help"):
            msg_payload = await studio_service.get_rendered_message(
                bot_id=bot_id,
                message_key="help",
                context=context,
                locale=user_locale,
            )
            reply_markup = None
            if msg_payload.get("keyboard"):
                reply_markup = msg_payload["keyboard"].model_dump(exclude_none=True)

            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=msg_payload["text"],
                reply_markup=reply_markup,
                parse_mode=msg_payload.get("parse_mode", "HTML"),
            )

        elif text.startswith("/lang") or text.startswith("/language"):
            lang_kb = build_language_keyboard()
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text="🌐 <b>Select Your Language / अपनी भाषा चुनें:</b>",
                reply_markup=lang_kb.model_dump(exclude_none=True),
                parse_mode="HTML",
            )

        elif text.startswith("set_lang:"):
            target_lang = text.split("set_lang:")[1].strip()
            new_lang = LocaleManager.normalize_locale(target_lang)
            user_record.preferred_locale = new_lang
            await self.db.flush()

            # Retrieve localized confirmation message from native i18n catalog
            loc_strings = TranslationRepository.load_file_translations(new_lang, "bot")
            conf_msg = loc_strings.get("language_changed", f"✅ Language updated to <b>{new_lang}</b>!")

            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text=conf_msg,
                parse_mode="HTML",
            )

        elif text.startswith("/menu") or text in ("⚡ Menu", "📋 Menu", "⚡ Command Menu"):
            reply_menu = await module_service.build_dynamic_reply_menu(bot_id)
            inline_menu = await module_service.build_dynamic_inline_menu(bot_id)
            if reply_menu:
                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text="⚡ <b>Mayagram Command Menu Active</b>",
                    reply_markup=reply_menu,
                    parse_mode="HTML",
                )
            await TelegramApiService.send_message_with_retry(
                raw_token=raw_token,
                chat_id=chat_id,
                text="🌟 <b>Feature Hub:</b> Select an option below to interact with the bot:",
                reply_markup=inline_menu,
                parse_mode="HTML",
            )

        else:
            # Fallback for unrecognized messages or conversational chat
            if text:
                inline_menu = await module_service.build_dynamic_inline_menu(bot_id)
                reply_menu = await module_service.build_dynamic_reply_menu(bot_id)
                if await module_service.is_module_active(bot_id, "ai_assistant"):
                    ai_reply = f"🤖 <b>AI Assistant:</b>\n\nI received your query: <i>\"{text}\"</i>\n\nHow can I help you today? Tap any feature button below or type /help."
                else:
                    ai_reply = "⚡ <b>Mayagram Feature Hub</b>\n\nPlease select an option below:"

                await TelegramApiService.send_message_with_retry(
                    raw_token=raw_token,
                    chat_id=chat_id,
                    text=ai_reply,
                    reply_markup=inline_menu,
                    parse_mode="HTML",
                )

        return {"ok": True, "processed": True}
