from pathlib import Path
from datetime import datetime, timedelta
import os
import json
import asyncio
import re
import shutil
import gc
import zipfile
import time
import threading
import traceback
from importlib import metadata as importlib_metadata
from urllib.parse import unquote

try:
    from balethon import Client as Bc
    from balethon.conditions import private
    from balethon.objects import Message, ReplyKeyboard
    from aiobale import Client, Dispatcher
    from aiobale.enums import AuthErrors, ChatType, PeerType, GroupType, GivingType
    from aiobale.methods import MessageSetReaction
    from aiobale.types import Peer
except ImportError as exc:
    raise SystemExit(
        "پیش‌نیازهای ربات نصب نیستند یا نسخه آن‌ها ناسازگار است.\n"
        "این دستور را اجرا کنید:\n"
        "pip install -U aiobale==0.1.5 Balethon==1.1.0\n\n"
        f"جزئیات: {exc}"
    ) from exc

BASE_DIR = Path(__file__).resolve().parent
SESSIONS_DIR = BASE_DIR / "sessions"
CHECK_DIR = BASE_DIR / "check"
DATA_DIR = BASE_DIR / "data"
QUARANTINE_DIR = BASE_DIR / "quarantine"
LOG_DIR = BASE_DIR / "logs"
PANEL_FILE = DATA_DIR / "panel.json"
SESSIONS_DB_FILE = BASE_DIR / "sessions.json"

SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
CHECK_DIR.mkdir(parents=True, exist_ok=True)
DATA_DIR.mkdir(parents=True, exist_ok=True)
QUARANTINE_DIR.mkdir(parents=True, exist_ok=True)
LOG_DIR.mkdir(parents=True, exist_ok=True)

DATA_LOCK = threading.RLock()
SESSION_FILE_LOCK = threading.RLock()

TOKEN_FILE = DATA_DIR / "bot_token.txt"
BOT_TOKEN = os.getenv("BALE_BOT_TOKEN", "").strip()
if not BOT_TOKEN and TOKEN_FILE.exists():
    try:
        BOT_TOKEN = TOKEN_FILE.read_text(encoding="utf-8").strip()
    except Exception:
        BOT_TOKEN = "567482402:gCjapQSFBheshMghUM-ABl42UZPrWhqdCAU"
if not BOT_TOKEN:
    raise SystemExit(
        "توکن ربات تنظیم نشده است. متغیر BALE_BOT_TOKEN را تنظیم کنید "
        "یا توکن را داخل data/bot_token.txt قرار دهید."
    )
bot = Bc(BOT_TOKEN)

admins = {1533487785, 1316869839}
reactions = [
    "❤️", "👍", "👎", "😂", "😭", "👌", "🙏",
    "🇮🇷", "🇵🇸", "🌷", "😍", "😎", "😱", "😡", "😐",
    "🤯", "🥳", "👏", "🤲", "🔥", "✅", "😔", "🖤"
]
user_data = {}
ACTIVE_OPERATIONS = {}
JOIN_GUARD_TASK = None
JOIN_GUARD_RUNNING = False
JOIN_GUARD_DEFAULT_INTERVAL = 600

MAX_ZIP_SESSION_COUNT = 2000
MAX_SESSION_FILE_SIZE = 10 * 1024 * 1024
MAX_ZIP_UNCOMPRESSED_SIZE = 250 * 1024 * 1024
MAX_UPLOAD_SIZE = 100 * 1024 * 1024

REQUIRED_AIOBALE_METHODS = {
    "get_me", "get_full_me", "load_dialogs", "get_full_group", "leave_group",
    "transfer_group_ownership", "get_wallet", "send_gift", "start_phone_auth",
    "validate_code", "validate_password", "load_user", "join_chat",
    "get_group_preview", "send_message", "load_history", "seen_chat",
    "set_reaction", "report_chat", "edit_name", "edit_about"
}
_missing_methods = sorted(name for name in REQUIRED_AIOBALE_METHODS if not hasattr(Client, name))
if _missing_methods:
    raise SystemExit(
        "نسخه aiobale با این ربات سازگار نیست. متدهای زیر وجود ندارند:\n"
        + ", ".join(_missing_methods)
        + "\n\nدستور اصلاح:\npip install -U aiobale==0.1.5"
    )
if not hasattr(GivingType, "SAME"):
    raise SystemExit(
        "نسخه aiobale با قابلیت پاکت سازگار نیست.\n"
        "دستور اصلاح:\npip install -U aiobale==0.1.5"
    )

MAIN_KEYBOARD = [
    ["📊 اطلاعات کامل"],
    ["📥 جوین دسته‌جمعی", "📤 لیو دسته‌جمعی"],
    ["🔍 بررسی سشن‌ها", "✨ ساخت سشن"],
    ["🚪 خروج همه از کانال‌ها و گروه‌ها"],
    ["💻 مدیریت سشن", "🎩 برترین ها"],
    ["⨻ گزارش"],
    ["📨 ارسال پیام"],
    ["📨 ارسال به همه پیوی", "📨 ارسال به همه گروه‌ها"],
    ["👁 واکنش", "🔁 سین", "📤 گزارش هوشمند"],
    ["⚙️ تنظیمات", "📦 دریافت بکاپ"],
    ["📚 راهنما"]
]

CONTROL_TEXTS = {
    "/start", "/cancel", "📊 اطلاعات کامل", "📥 جوین دسته‌جمعی",
    "📤 لیو دسته‌جمعی", "🔍 بررسی سشن‌ها", "✨ ساخت سشن",
    "🚪 خروج همه از کانال‌ها و گروه‌ها", "💻 مدیریت سشن",
    "🎩 برترین ها", "⚙️ تنظیمات", "📦 دریافت بکاپ", "📚 راهنما", "⨠ به روزرسانی دیتابیس", "🔍 سرچ سشن",
    "⪢ ورود به اکانت", "🔙 بازگشت", "⏱ تغییر Delay",
    "🧹 پاکسازی گروه‌های ذخیره‌شده", "✅ تایید خروج همه",
    "❌ لغو خروج", "📱 شماره‌ها", "ℹ️ اطلاعات سشن",
    "📚 همه کانال‌ها و گروه‌ها", "👑 مالکیت‌های سشن‌ها",
    "👑 انتقال مالکیت", "💰 تجمیع موجودی",
    "✅ تایید انتقال مالکیت", "❌ لغو انتقال مالکیت",
    "✅ تایید ارسال پاکت‌ها", "❌ لغو ارسال پاکت‌ها",
    "🛡 محافظ عضویت", "✅ فعال‌سازی محافظ", "⛔ غیرفعال‌سازی محافظ",
    "🔎 بررسی عضویت‌ها الان", "📋 لیست مجازها",
    "🗑 پاک کردن لیست مجازها", "✅ تایید پاک‌کردن مجازها",
    "❌ لغو پاک‌کردن مجازها",
    "⨻ گزارش", "📨 ارسال به همه پیوی", "📨 ارسال به همه گروه‌ها",
    "👁 واکنش", "🔁 سین", "📤 گزارش هوشمند", "📨 ارسال پیام",
    "✅ تایید ارسال پیوی", "✅ تایید ارسال گروه‌ها", "✅ تایید ارسال پیام",
    "➕ افزودن پیوی مجاز", "➖ حذف پیوی مجاز", "📋 پیوی‌های مجاز",
    "❌ لغو ارسال همگانی", "✅ تایید گزارش", "❌ لغو گزارش",
    "📞 شماره از نام فایل", "✏️ تغییر نام همه", "🧹 پاک کردن بیو همه",
    "✅ تایید تغییر نام همه", "❌ لغو تغییر نام همه",
    "✅ تایید پاک کردن بیو همه", "❌ لغو پاک کردن بیو همه",
}


def convert_to_english_numbers(text):
    text = "" if text is None else str(text)
    table = str.maketrans({
        "۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4",
        "۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9",
        "٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4",
        "٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9"
    })
    return text.translate(table)


def get_valid_phone_number(text):
    phone = re.sub(r"\D", "", convert_to_english_numbers(text))
    if phone.startswith("00"):
        phone = phone[2:]
    if phone.startswith("0") and len(phone) == 11:
        phone = "98" + phone[1:]
    elif phone.startswith("9") and len(phone) == 10:
        phone = "98" + phone
    if re.fullmatch(r"989\d{9}", phone):
        return phone
    return None


def iv(value):
    return getattr(value, "value", value)


def default_panel_data():
    return {
        "delay": 2,
        "group": [],
        "allowed_chat_ids": [],
        "allowed_private_ids": [],
        "join_guard_enabled": False,
        "join_guard_interval": JOIN_GUARD_DEFAULT_INTERVAL
    }


def atomic_write_json(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp_path = path.with_name(f".{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
    try:
        with temp_path.open("w", encoding="utf-8") as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
            file.flush()
            os.fsync(file.fileno())
        os.replace(temp_path, path)
    finally:
        try:
            temp_path.unlink()
        except FileNotFoundError:
            pass
        except Exception:
            pass


def save_data(data):
    with DATA_LOCK:
        atomic_write_json(PANEL_FILE, data)


def get_data():
    with DATA_LOCK:
        must_save = False
        if not PANEL_FILE.exists():
            data = default_panel_data()
            must_save = True
        else:
            try:
                with PANEL_FILE.open("r", encoding="utf-8") as file:
                    data = json.load(file)
                if not isinstance(data, dict):
                    raise ValueError("invalid panel data")
            except Exception:
                data = default_panel_data()
                must_save = True

        original = dict(data)
        data.setdefault("delay", 2)
        data.setdefault("group", [])
        data.setdefault("allowed_chat_ids", [])
        data.setdefault("join_guard_enabled", False)
        data.setdefault("join_guard_interval", JOIN_GUARD_DEFAULT_INTERVAL)
        if not isinstance(data["group"], list):
            data["group"] = []
        if not isinstance(data["allowed_chat_ids"], list):
            data["allowed_chat_ids"] = []
        cleaned_ids = []
        for item in data["allowed_chat_ids"]:
            try:
                value = int(item)
                if value > 0 and value not in cleaned_ids:
                    cleaned_ids.append(value)
            except Exception:
                pass
        data["allowed_chat_ids"] = cleaned_ids
        data["join_guard_enabled"] = bool(data["join_guard_enabled"])
        try:
            data["join_guard_interval"] = max(300, min(3600, int(data["join_guard_interval"])))
        except Exception:
            data["join_guard_interval"] = JOIN_GUARD_DEFAULT_INTERVAL
        try:
            data["delay"] = max(0, int(data["delay"]))
        except Exception:
            data["delay"] = 2
        if must_save or data != original:
            atomic_write_json(PANEL_FILE, data)
        return data


def get_delay():
    return get_data()["delay"]


def add_group(group):
    data = get_data()
    if group not in data["group"]:
        data["group"].append(group)
        save_data(data)


def remove_group(group):
    data = get_data()
    if group in data["group"]:
        data["group"].remove(group)
        save_data(data)


def clear_groups():
    data = get_data()
    data["group"] = []
    save_data(data)


def get_group():
    return list(get_data()["group"])


def get_allowed_chat_ids():
    return set(get_data().get("allowed_chat_ids", []))


def get_allowed_private_ids():
    return set(get_data().get("allowed_private_ids", []))


def add_allowed_private_id(chat_id):
    try:
        chat_id = int(chat_id)
    except Exception:
        return False
    if chat_id <= 0:
        return False
    data = get_data()
    ids = list(dict.fromkeys(int(item) for item in data.get("allowed_private_ids", []) if str(item).isdigit()))
    if chat_id not in ids:
        ids.append(chat_id)
        data["allowed_private_ids"] = ids
        save_data(data)
    return True


def remove_allowed_private_id(chat_id):
    try:
        chat_id = int(chat_id)
    except Exception:
        return False
    data = get_data()
    ids = [int(item) for item in data.get("allowed_private_ids", []) if str(item).isdigit()]
    if chat_id not in ids:
        return False
    data["allowed_private_ids"] = [item for item in ids if item != chat_id]
    save_data(data)
    return True


def add_allowed_chat_id(chat_id):
    try:
        chat_id = int(chat_id)
    except Exception:
        return False
    if chat_id <= 0:
        return False
    data = get_data()
    ids = []
    for item in data.get("allowed_chat_ids", []):
        try:
            value = int(item)
            if value > 0 and value not in ids:
                ids.append(value)
        except Exception:
            pass
    if chat_id not in ids:
        ids.append(chat_id)
        data["allowed_chat_ids"] = ids
        save_data(data)
    return True


def clear_join_allowlist():
    data = get_data()
    data["group"] = []
    data["allowed_chat_ids"] = []
    data["join_guard_enabled"] = False
    save_data(data)


def is_join_guard_enabled():
    return bool(get_data().get("join_guard_enabled", False))


def set_join_guard_enabled(enabled):
    data = get_data()
    data["join_guard_enabled"] = bool(enabled)
    save_data(data)


def get_join_guard_interval():
    return int(get_data().get("join_guard_interval", JOIN_GUARD_DEFAULT_INTERVAL))


def get_session_files():
    SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
    return sorted([path for path in SESSIONS_DIR.iterdir() if path.is_file() and path.suffix.lower() == ".bale"])


def progress_step(total):
    return max(1, total // 10) if total else 1


def should_update(index, total):
    return index == total or index % progress_step(total) == 0


def state_action(user_id):
    state = user_data.get(user_id)
    if isinstance(state, dict):
        return state.get("action")
    return state


def sanitize_upload_name(file_name, default="session.bale"):
    safe_name = os.path.basename(str(file_name or default)).strip() or default
    safe_name = re.sub(r"[^0-9A-Za-z._() -]+", "_", safe_name)
    return safe_name[:120]


def unique_session_path(file_name):
    safe_name = sanitize_upload_name(file_name)
    if not safe_name.lower().endswith(".bale"):
        safe_name += ".bale"
    candidate = SESSIONS_DIR / safe_name
    if not candidate.exists():
        return candidate
    stem = candidate.stem
    suffix = candidate.suffix
    counter = 2
    while True:
        alternative = SESSIONS_DIR / f"{stem}_{counter}{suffix}"
        if not alternative.exists():
            return alternative
        counter += 1


def copy_session_unique(source_path, file_name):
    with SESSION_FILE_LOCK:
        destination = unique_session_path(file_name)
        shutil.copyfile(source_path, destination)
        return destination


def get_document_size(document):
    for attr in ("file_size", "size"):
        value = getattr(document, attr, None)
        try:
            if value is not None:
                return int(value)
        except Exception:
            pass
    return None


def unlink_quietly(path):
    try:
        Path(path).unlink()
        return True
    except FileNotFoundError:
        return True
    except Exception:
        return False


async def safe_edit(target_message, *args, **kwargs):
    try:
        return await target_message.edit_text(*args, **kwargs)
    except Exception as exc:
        print(f"edit_text warning: {type(exc).__name__}: {exc}")
        return None


def active_operation_name(entry):
    if isinstance(entry, dict):
        return str(entry.get("name") or "عملیات فعال")
    return str(entry or "عملیات فعال")


async def _operation_runner(message, user_id, operation_name, operation, args, kwargs):
    try:
        await operation(*args, **kwargs)
    except asyncio.CancelledError:
        try:
            await message.reply(
                f"⏹ عملیات «{operation_name}» متوقف شد.",
                ReplyKeyboard(*MAIN_KEYBOARD)
            )
        except Exception:
            pass
    except Exception as exc:
        try:
            await message.reply(
                f"❌ عملیات «{operation_name}» با خطا متوقف شد:\n{type(exc).__name__}: {exc}",
                ReplyKeyboard(*MAIN_KEYBOARD)
            )
        except Exception:
            pass
    finally:
        current = ACTIVE_OPERATIONS.get(user_id)
        if isinstance(current, dict) and current.get("task") is asyncio.current_task():
            ACTIVE_OPERATIONS.pop(user_id, None)


async def run_exclusive(message, operation_name, operation, *args, **kwargs):
    user_id = message.author.id
    current = ACTIVE_OPERATIONS.get(user_id)
    if current:
        await message.reply(
            f"⏳ عملیات «{active_operation_name(current)}» هنوز در حال اجراست. "
            "برای توقف از /cancel یا دکمه لغو استفاده کنید."
        )
        return None

    task = asyncio.create_task(
        _operation_runner(message, user_id, operation_name, operation, args, kwargs)
    )
    ACTIVE_OPERATIONS[user_id] = {
        "name": operation_name,
        "task": task,
        "started_at": datetime.now()
    }

    def cleanup_finished_operation(done_task):
        current_entry = ACTIVE_OPERATIONS.get(user_id)
        if isinstance(current_entry, dict) and current_entry.get("task") is done_task:
            ACTIVE_OPERATIONS.pop(user_id, None)

    task.add_done_callback(cleanup_finished_operation)
    await message.reply(
        f"✅ عملیات «{operation_name}» در پس‌زمینه شروع شد.\n"
        "ربات قفل نمی‌شود و برای توقف می‌توانید /cancel را بفرستید."
    )
    return task


async def cancel_active_operation(message, user_id):
    current = ACTIVE_OPERATIONS.get(user_id)
    if not current:
        return False
    task = current.get("task") if isinstance(current, dict) else None
    operation_name = active_operation_name(current)
    if task is not None and not task.done():
        task.cancel()
        await message.reply(f"⏳ درخواست توقف عملیات «{operation_name}» ثبت شد...")
    else:
        ACTIVE_OPERATIONS.pop(user_id, None)
        await message.reply(f"⏹ عملیات «{operation_name}» قبلاً متوقف شده است.")
    return True


async def safe_stop(client):
    if client is None:
        return
    try:
        await asyncio.wait_for(client.stop(), timeout=10)
        return
    except asyncio.CancelledError:
        try:
            session = getattr(client, "session", None)
            if session is not None and hasattr(session, "close"):
                result = session.close()
                if asyncio.iscoroutine(result):
                    await asyncio.shield(asyncio.wait_for(result, timeout=5))
        except BaseException:
            pass
        raise
    except Exception:
        pass
    try:
        session = getattr(client, "session", None)
        if session is not None and hasattr(session, "close"):
            result = session.close()
            if asyncio.iscoroutine(result):
                await asyncio.wait_for(result, timeout=5)
    except Exception:
        pass


async def validate_session_file(path):
    client = None
    try:
        client = Client(Dispatcher(), session_file=str(path))
        me = await asyncio.wait_for(client.get_me(), timeout=35)
        return True, me, None
    except Exception as exc:
        return False, None, str(exc)
    finally:
        await safe_stop(client)


async def get_healthy_session_paths(limit=None, progress_message=None):
    files = get_session_files()
    healthy = []
    for index, path in enumerate(files, 1):
        ok, _, _ = await validate_session_file(path)
        if ok:
            healthy.append(path)
        if progress_message and should_update(index, len(files)):
            await safe_edit(progress_message, 
                f"🔄 در حال بررسی سشن‌ها... ({index} از {len(files)})\n"
                f"✅ سالم: {len(healthy)}"
            )
        if limit is not None and len(healthy) >= limit:
            break
    return healthy


def as_int(value, default=0):
    try:
        return int(iv(value))
    except Exception:
        return default


def as_bool(value):
    value = iv(value)
    if isinstance(value, str):
        return value.strip().lower() in {"1", "true", "yes", "on"}
    return bool(value)


def clean_phone(value, file_name=""):
    raw = re.sub(r"\D", "", str(iv(value) or ""))
    if re.fullmatch(r"989\d{9}", raw):
        return raw
    stem = convert_to_english_numbers(Path(str(file_name or "")).stem)
    match = re.search(r"(?<!\d)(989\d{9})(?!\d)", stem)
    if match:
        return match.group(1)
    from_file = re.sub(r"\D", "", stem)
    if re.fullmatch(r"989\d{9}", from_file):
        return from_file
    return raw or "نامشخص"


def mask_value(value, keep_start=4, keep_end=4):
    text = str(value or "")
    if not text:
        return "ندارد"
    if len(text) <= keep_start + keep_end:
        return "*" * len(text)
    return text[:keep_start] + "*" * (len(text) - keep_start - keep_end) + text[-keep_end:]


def format_timestamp(value):
    timestamp = as_int(value, 0)
    if not timestamp:
        return "نامشخص"
    if timestamp > 10_000_000_000:
        timestamp = timestamp / 1000
    try:
        return datetime.fromtimestamp(timestamp).strftime("%Y/%m/%d %H:%M:%S")
    except Exception:
        return str(value)


def group_type_name(value):
    number = as_int(value, -1)
    names = {
        as_int(GroupType.GROUP): "گروه",
        as_int(GroupType.CHANNEL): "کانال",
        as_int(GroupType.SUPERGROUP): "سوپرگروه"
    }
    return names.get(number, f"نامشخص({number})")


def split_long_text(text, limit=3400):
    text = str(text)
    if len(text) <= limit:
        return [text]
    chunks = []
    current = []
    current_len = 0
    for line in text.splitlines(True):
        if len(line) > limit:
            if current:
                chunks.append("".join(current))
                current = []
                current_len = 0
            for index in range(0, len(line), limit):
                chunks.append(line[index:index + limit])
            continue
        if current_len + len(line) > limit and current:
            chunks.append("".join(current))
            current = []
            current_len = 0
        current.append(line)
        current_len += len(line)
    if current:
        chunks.append("".join(current))
    return chunks


async def send_text_chunks(message, text):
    for chunk in split_long_text(text):
        await message.reply(chunk)


async def send_text_report(message, title, lines, file_name):
    report_path = CHECK_DIR / f"{Path(file_name).stem}_{message.author.id}_{time.time_ns()}.txt"
    content = title + "\n\n" + "\n".join(lines)
    report_path.write_text(content, encoding="utf-8")
    try:
        await message.reply_document(str(report_path), title)
    finally:
        try:
            report_path.unlink()
        except Exception:
            pass


async def load_all_group_dialogs(client):
    found = {}
    offset_date = -1
    seen_offsets = set()
    seen_pages = set()
    preferred_limit = 40

    for page_index in range(1000):
        dialogs = None
        last_error = None
        trial_limits = []
        current_limit = preferred_limit
        while current_limit >= 1:
            if current_limit not in trial_limits:
                trial_limits.append(current_limit)
            if current_limit == 1:
                break
            current_limit = max(1, current_limit // 2)

        for page_limit in trial_limits:
            try:
                dialogs = await asyncio.wait_for(
                    client.load_dialogs(
                        limit=page_limit,
                        offset_date=offset_date,
                        exclude_pinned=page_index > 0
                    ),
                    timeout=25
                )
                preferred_limit = page_limit
                break
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                last_error = exc
                error_text = f"{type(exc).__name__}: {exc}".lower()
                tail_validation_error = (
                    "validationerror" in error_text
                    or "validation error" in error_text
                    or "peerdata" in error_text
                    or "none is not an allowed value" in error_text
                )
                if not tail_validation_error:
                    raise

        if dialogs is None:
            if found:
                break
            if last_error is not None:
                error_text = f"{type(last_error).__name__}: {last_error}".lower()
                if "validation" in error_text or "peerdata" in error_text:
                    return []
                raise last_error
            break
        if not dialogs:
            break

        page_signature = []
        page_dates = []
        for dialog in dialogs:
            peer = getattr(dialog, "peer", None)
            if peer is None:
                continue
            peer_type = as_int(getattr(peer, "type", 0))
            peer_id = as_int(getattr(peer, "id", 0))
            sort_date = as_int(getattr(dialog, "sort_date", 0))
            page_signature.append((peer_type, peer_id, sort_date))
            if peer_type == as_int(PeerType.GROUP) and peer_id:
                found[peer_id] = {
                    "id": peer_id,
                    "sort_date": sort_date
                }
            if sort_date > 0:
                page_dates.append(sort_date)

        signature = tuple(page_signature)
        if signature in seen_pages:
            break
        seen_pages.add(signature)

        if not page_dates:
            break
        next_offset = min(page_dates) - 1
        if next_offset in seen_offsets:
            break
        if offset_date != -1 and next_offset >= offset_date:
            break
        seen_offsets.add(next_offset)
        offset_date = next_offset

        if len(dialogs) < preferred_limit:
            break

    return sorted(found.values(), key=lambda item: item["sort_date"], reverse=True)


async def load_all_group_dialog_ids(client):
    return [item["id"] for item in await load_all_group_dialogs(client)]


async def resolve_allowed_chat_ids(client):
    allowed_ids = set(get_allowed_chat_ids())
    unresolved_links = []
    changed = False
    for link in get_group():
        try:
            preview = await asyncio.wait_for(client.get_group_preview(link), timeout=20)
            chat_id = as_int(getattr(preview, "id", 0))
            if chat_id <= 0:
                unresolved_links.append(link)
                continue
            if chat_id not in allowed_ids:
                allowed_ids.add(chat_id)
                changed = True
        except asyncio.CancelledError:
            raise
        except Exception:
            unresolved_links.append(link)
    if changed:
        data = get_data()
        data["allowed_chat_ids"] = sorted(allowed_ids)
        save_data(data)
    return allowed_ids, unresolved_links


async def run_membership_guard_once(message=None):
    global JOIN_GUARD_RUNNING
    if JOIN_GUARD_RUNNING:
        if message is not None:
            await message.reply("⏳ محافظ عضویت هم‌اکنون در حال بررسی است.")
        return None

    files = get_session_files()
    if not files:
        if message is not None:
            await message.reply("📭 سشنی برای بررسی وجود ندارد.")
        return None

    if not get_group() and not get_allowed_chat_ids():
        if message is not None:
            await message.reply(
                "⚠️ لیست مجاز خالی است. برای جلوگیری از خروج اشتباهی، محافظ اجرا نشد.\n"
                "ابتدا با دستور «عضو شو» حداقل یک لینک مجاز ثبت کنید."
            )
        return None

    JOIN_GUARD_RUNNING = True
    progress = None
    if message is not None:
        progress = await message.reply("🛡 بررسی عضویت‌های غیرمجاز شروع شد...")

    stats = {
        "sessions": len(files),
        "healthy": 0,
        "bad": 0,
        "dialogs": 0,
        "unauthorized": 0,
        "left": 0,
        "owners": 0,
        "failed": 0,
    }
    errors = []
    allowed_ids = set(get_allowed_chat_ids())
    allowlist_refreshed = False

    try:
        for index, path in enumerate(files, 1):
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                identity = await asyncio.wait_for(get_account_identity(client, path), timeout=35)
                stats["healthy"] += 1

                if not allowlist_refreshed:
                    allowed_ids, unresolved_links = await resolve_allowed_chat_ids(client)
                    allowlist_refreshed = True
                    if unresolved_links:
                        if progress is not None:
                            await safe_edit(
                                progress,
                                "⚠️ بعضی لینک‌های مجاز قابل تبدیل به آیدی نبودند؛ "
                                "برای جلوگیری از خروج اشتباهی، عملیات متوقف شد."
                            )
                        return stats
                    if not allowed_ids:
                        if progress is not None:
                            await safe_edit(
                                progress,
                                "⚠️ هیچ آیدی معتبری از لینک‌های مجاز استخراج نشد؛ "
                                "برای جلوگیری از خروج اشتباهی، عملیات متوقف شد."
                            )
                        return stats

                dialogs = await load_all_group_dialogs(client)
                stats["dialogs"] += len(dialogs)

                for dialog in dialogs:
                    chat_id = int(dialog["id"])
                    if chat_id in allowed_ids:
                        continue

                    stats["unauthorized"] += 1
                    is_owner = False
                    try:
                        full_group = await asyncio.wait_for(client.get_full_group(chat_id), timeout=15)
                        is_owner = as_int(getattr(full_group, "owner_id", 0)) == identity["id"]
                    except asyncio.CancelledError:
                        raise
                    except Exception:
                        pass

                    if is_owner:
                        stats["owners"] += 1
                        continue

                    try:
                        await asyncio.wait_for(client.leave_group(chat_id), timeout=25)
                        stats["left"] += 1
                    except asyncio.CancelledError:
                        raise
                    except Exception as exc:
                        stats["failed"] += 1
                        errors.append(f"{path.name} | {chat_id}: {type(exc).__name__}: {exc}")

                    delay = min(max(float(get_delay()), 0.0), 3.0)
                    if delay:
                        await asyncio.sleep(delay)

            except asyncio.CancelledError:
                raise
            except Exception as exc:
                stats["bad"] += 1
                errors.append(f"{path.name}: {type(exc).__name__}: {exc}")
            finally:
                await safe_stop(client)

            if progress is not None and should_update(index, len(files)):
                await safe_edit(
                    progress,
                    "🛡 محافظ عضویت\n\n"
                    f"سشن بررسی‌شده: {index} از {len(files)}\n"
                    f"گفتگوها: {stats['dialogs']}\n"
                    f"عضویت غیرمجاز: {stats['unauthorized']}\n"
                    f"خروج موفق: {stats['left']}\n"
                    f"مالک و ردشده: {stats['owners']}\n"
                    f"ناموفق: {stats['failed']}"
                )

        summary = (
            "✅ بررسی محافظ عضویت تمام شد.\n\n"
            f"📁 سشن‌ها: {stats['sessions']}\n"
            f"✅ سالم: {stats['healthy']}\n"
            f"❌ خراب/خطادار: {stats['bad']}\n"
            f"📚 گفتگوهای بررسی‌شده: {stats['dialogs']}\n"
            f"🚫 عضویت غیرمجاز: {stats['unauthorized']}\n"
            f"🚶 خروج موفق: {stats['left']}\n"
            f"👑 مالک و خارج‌نشده: {stats['owners']}\n"
            f"⚠️ خروج ناموفق: {stats['failed']}"
        )
        if progress is not None:
            await safe_edit(progress, summary)
        if errors and message is not None:
            await send_text_report(message, "گزارش خطاهای محافظ عضویت", errors, "join_guard_errors.txt")
        return stats
    finally:
        JOIN_GUARD_RUNNING = False


async def join_guard_loop():
    while True:
        try:
            if not is_join_guard_enabled():
                return
            stats = await run_membership_guard_once()
            if stats and (stats["left"] or stats["failed"] or stats["owners"]):
                report = (
                    "🛡 گزارش خودکار محافظ عضویت\n\n"
                    f"🚫 غیرمجاز: {stats['unauthorized']}\n"
                    f"🚶 خروج موفق: {stats['left']}\n"
                    f"👑 مالک و ردشده: {stats['owners']}\n"
                    f"⚠️ ناموفق: {stats['failed']}"
                )
                for admin_id in admins:
                    if admin_id:
                        try:
                            await bot.send_message(admin_id, report)
                        except Exception:
                            pass
            await asyncio.sleep(get_join_guard_interval())
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            print(f"join guard warning: {type(exc).__name__}: {exc}")
            await asyncio.sleep(60)


def ensure_join_guard_task():
    global JOIN_GUARD_TASK
    if not is_join_guard_enabled():
        return None
    if JOIN_GUARD_TASK is None or JOIN_GUARD_TASK.done():
        JOIN_GUARD_TASK = asyncio.create_task(join_guard_loop())
    return JOIN_GUARD_TASK


async def stop_join_guard_task():
    global JOIN_GUARD_TASK
    task = JOIN_GUARD_TASK
    JOIN_GUARD_TASK = None
    if task is not None and not task.done():
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass
        except Exception:
            pass


async def get_account_identity(client, path):
    me = await asyncio.wait_for(client.get_me(), timeout=35)
    full = None
    try:
        full = await asyncio.wait_for(client.get_full_me(), timeout=45)
    except Exception:
        pass
    contact = getattr(full, "contact_info", None) if full is not None else None
    phone = clean_phone(getattr(contact, "value", ""), path.name)
    username = str(iv(getattr(me, "username", "")) or "")
    return {
        "me": me,
        "full": full,
        "id": as_int(getattr(me, "id", 0)),
        "name": str(getattr(me, "name", "") or "بدون نام"),
        "username": username,
        "phone": phone,
        "file": path.name
    }


async def get_coder(session_file, admin):
    client = None
    task = None
    try:
        dp = Dispatcher()
        client = Client(dp, session_file=str(SESSIONS_DIR / session_file))

        @dp.message()
        async def receive_code(msg):
            if msg.text and "code" in msg.text.lower():
                await bot.send_message(admin, msg.text)

        task = asyncio.create_task(client.start())
        await asyncio.sleep(60)
        await bot.send_message(admin, "✅ زمان بررسی پیام‌های کد به پایان رسید.")
    except Exception as exc:
        await bot.send_message(admin, f"❌ ارتباط با سشن ممکن نشد:\n{exc}")
    finally:
        if task is not None:
            task.cancel()
            try:
                await task
            except BaseException:
                pass
        await safe_stop(client)


def auth_error_message(error):
    messages = {
        AuthErrors.NUMBER_BANNED: "🚫 این شماره مسدود شده است.",
        AuthErrors.AUTH_LIMIT: "⏳ تعداد تلاش‌های ورود بیش از حد مجاز است.",
        AuthErrors.RATE_LIMIT: "⏳ درخواست‌های زیادی ارسال شده؛ کمی بعد دوباره امتحان کنید.",
        AuthErrors.INVALID: "⚠️ شماره تلفن توسط بله نامعتبر تشخیص داده شد.",
        AuthErrors.SIGN_UP_NEEDED: "⚠️ برای این شماره حساب بله ساخته نشده است.",
        AuthErrors.UNKNOWN: "❌ خطای ناشناخته در احراز هویت رخ داد."
    }
    return messages.get(error, f"❌ خطای احراز هویت: {error}")


async def finalize_created_session(message, user_id, session_path):
    await asyncio.sleep(0.2)
    ok, me, error = await validate_session_file(session_path)
    user_data.pop(user_id, None)
    if not ok:
        unlink_quietly(session_path)
        await message.reply(
            "❌ ورود ظاهراً انجام شد، اما فایل سشن قابل استفاده ساخته نشد.\n"
            f"جزئیات: {error}"
        )
        return False
    await message.reply(
        "🎉 ورود موفق بود و سشن سالم ذخیره شد.\n"
        f"📁 نام فایل: {session_path.name}\n"
        f"🆔 آیدی حساب: {getattr(me, 'id', 'نامشخص')}"
    )
    return True


async def discard_incomplete_auth(user_id):
    state = user_data.pop(user_id, None)
    if isinstance(state, dict) and state.get("phone"):
        unlink_quietly(SESSIONS_DIR / f"{state['phone']}.bale")


async def start_session_auth(message, user_id, text):
    phone_number = get_valid_phone_number(text)
    if not phone_number:
        await message.reply(
            "⚠️ شماره تلفن نامعتبر\n\n"
            "شماره را با یکی از این فرمت‌ها بفرستید:\n"
            "• 989123456789\n"
            "• +989123456789\n"
            "• 09123456789\n"
            "• 9123456789\n\n"
            "لغو عملیات: /cancel"
        )
        return

    session_path = SESSIONS_DIR / f"{phone_number}.bale"
    if session_path.exists():
        ok, _, _ = await validate_session_file(session_path)
        if ok:
            user_data.pop(user_id, None)
            await message.reply("✅ سشن این شماره از قبل وجود دارد و سالم است.")
            return
        unlink_quietly(session_path)

    client = None
    keep_incomplete_file = False
    try:
        client = Client(Dispatcher(), session_file=str(session_path))
        result = await asyncio.wait_for(
            client.start_phone_auth(phone_number=int(phone_number)),
            timeout=45
        )
        if isinstance(result, AuthErrors):
            await message.reply(auth_error_message(result))
            return
        transaction_hash = getattr(result, "transaction_hash", None)
        if not transaction_hash:
            await message.reply("❌ پاسخ ارسال کد معتبر نبود. دوباره تلاش کنید.")
            return
        keep_incomplete_file = True
        user_data[user_id] = {
            "action": "create_session_code",
            "send_time": datetime.now(),
            "transaction_hash": transaction_hash,
            "code_attempts": 0,
            "password_attempts": 0,
            "phone": phone_number
        }
        await message.reply(
            f"📨 کد تأیید برای شماره {phone_number} ارسال شد.\n"
            "⏰ تا ۹۰ ثانیه کد را وارد کنید.\n"
            "🔢 کد را فقط به‌صورت عدد ارسال کنید."
        )
    except Exception as exc:
        await message.reply(f"❌ خطا در ارسال کد:\n{exc}")
    finally:
        await safe_stop(client)
        if not keep_incomplete_file:
            unlink_quietly(session_path)


async def validate_session_code(message, user_id, text):
    state = user_data.get(user_id, {})
    if datetime.now() - state.get("send_time", datetime.min) > timedelta(seconds=90):
        await discard_incomplete_auth(user_id)
        await message.reply("⏰ زمان وارد کردن کد تمام شد. دوباره «ساخت سشن» را بزنید.")
        return

    code = re.sub(r"\D", "", convert_to_english_numbers(text))
    if not code:
        await message.reply("📝 لطفاً کد را فقط به‌صورت عدد وارد کنید.")
        return

    client = None
    phone = state.get("phone")
    if not phone or not state.get("transaction_hash"):
        await discard_incomplete_auth(user_id)
        await message.reply("❌ اطلاعات ورود ناقص است؛ دوباره «ساخت سشن» را بزنید.")
        return
    session_path = SESSIONS_DIR / f"{phone}.bale"
    login_succeeded = False
    try:
        client = Client(Dispatcher(), session_file=str(session_path))
        result = await asyncio.wait_for(
            client.validate_code(code=code, transaction_hash=state["transaction_hash"]),
            timeout=45
        )
        if isinstance(result, AuthErrors):
            if result == AuthErrors.WRONG_CODE:
                state["code_attempts"] = int(state.get("code_attempts", 0)) + 1
                if state["code_attempts"] >= 3:
                    await discard_incomplete_auth(user_id)
                    await message.reply("🚫 کد چند بار اشتباه بود؛ عملیات لغو شد.")
                else:
                    await message.reply(
                        f"❌ کد اشتباه است. فرصت باقی‌مانده: {3 - state['code_attempts']} بار"
                    )
                return
            if result == AuthErrors.PASSWORD_NEEDED:
                state["action"] = "create_session_password"
                await message.reply("🔐 تأیید دو مرحله‌ای فعال است؛ رمز عبور را ارسال کنید.")
                return
            await discard_incomplete_auth(user_id)
            await message.reply(auth_error_message(result))
            return
        login_succeeded = True
    except Exception as exc:
        await message.reply(f"⚠️ خطا در تأیید کد:\n{exc}")
    finally:
        await safe_stop(client)

    if login_succeeded:
        await finalize_created_session(message, user_id, session_path)


async def validate_session_password(message, user_id, password):
    state = user_data.get(user_id, {})
    phone = state.get("phone")
    if not phone or not state.get("transaction_hash"):
        await discard_incomplete_auth(user_id)
        await message.reply("❌ اطلاعات ورود ناقص است؛ دوباره «ساخت سشن» را بزنید.")
        return
    client = None
    session_path = SESSIONS_DIR / f"{phone}.bale"
    login_succeeded = False
    try:
        client = Client(Dispatcher(), session_file=str(session_path))
        result = await asyncio.wait_for(
            client.validate_password(password, state["transaction_hash"]),
            timeout=45
        )
        if isinstance(result, AuthErrors):
            if result == AuthErrors.WRONG_PASSWORD:
                state["password_attempts"] = int(state.get("password_attempts", 0)) + 1
                if state["password_attempts"] >= 3:
                    await discard_incomplete_auth(user_id)
                    await message.reply("🚫 رمز چند بار اشتباه بود؛ عملیات لغو شد.")
                else:
                    await message.reply(
                        f"🔒 رمز اشتباه است. فرصت باقی‌مانده: {3 - state['password_attempts']} بار"
                    )
                return
            await discard_incomplete_auth(user_id)
            await message.reply(auth_error_message(result))
            return
        login_succeeded = True
    except Exception as exc:
        await message.reply(f"⚠️ خطا در بررسی رمز:\n{exc}")
    finally:
        await safe_stop(client)

    if login_succeeded:
        await finalize_created_session(message, user_id, session_path)


def quarantine_session_file(path, reason):
    path = Path(path)
    QUARANTINE_DIR.mkdir(parents=True, exist_ok=True)
    safe_reason = re.sub(r"[^a-zA-Z0-9_-]+", "_", str(reason or "unknown"))
    destination = QUARANTINE_DIR / f"{path.stem}_{safe_reason}_{time.time_ns()}{path.suffix}"
    with SESSION_FILE_LOCK:
        shutil.move(str(path), str(destination))
    return destination


async def check_and_clean_sessions(message):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ فایل سشنی در پوشه sessions وجود ندارد.")
        return
    start = await message.reply("🔍 بررسی سشن‌ها شروع شد...")
    ok_count = 0
    bad_count = 0
    duplicate_count = 0
    quarantine_failed = 0
    account_ids = {}

    for index, path in enumerate(files, 1):
        ok, me, _ = await validate_session_file(path)
        quarantine_reason = None
        if not ok:
            bad_count += 1
            quarantine_reason = "invalid"
        else:
            account_id = int(me.id)
            if account_id in account_ids:
                duplicate_count += 1
                quarantine_reason = "duplicate"
            else:
                account_ids[account_id] = path.name
                ok_count += 1
        if quarantine_reason:
            try:
                quarantine_session_file(path, quarantine_reason)
            except Exception:
                quarantine_failed += 1
        if should_update(index, len(files)):
            await safe_edit(start,
                f"🔍 بررسی شده: {index} از {len(files)}\n"
                f"✅ سالم: {ok_count}\n"
                f"❌ خراب: {bad_count}\n"
                f"♻️ تکراری: {duplicate_count}"
            )

    await safe_edit(start,
        "✅ بررسی سشن‌ها تمام شد.\n\n"
        f"📊 کل: {len(files)}\n"
        f"✅ سالم: {ok_count}\n"
        f"❌ خراب و قرنطینه‌شده: {bad_count}\n"
        f"♻️ تکراری و قرنطینه‌شده: {duplicate_count}\n"
        f"⚠️ خطای انتقال به قرنطینه: {quarantine_failed}\n"
        f"📁 مسیر قرنطینه: {QUARANTINE_DIR.name}/"
    )


async def leave_all_groups_for_all_sessions(message):
    files = get_session_files()
    if not files:
        await message.reply("📭 سشنی برای انجام عملیات وجود ندارد.")
        return

    start = await message.reply(
        "🚪 خروج همگانی شروع شد. این عملیات در پس‌زمینه اجرا می‌شود و ربات قفل نمی‌شود."
    )
    healthy_sessions = 0
    bad_sessions = 0
    scan_failed_sessions = 0
    total_found = 0
    left_count = 0
    failed_count = 0
    owner_skipped = 0
    errors = []
    delay = max(0.0, min(float(get_delay()), 5.0))

    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            try:
                identity = await asyncio.wait_for(get_account_identity(client, path), timeout=35)
                healthy_sessions += 1
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                bad_sessions += 1
                errors.append(f"{path.name}: خطای سشن: {exc}")
                continue

            try:
                dialogs = await load_all_group_dialogs(client)
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                scan_failed_sessions += 1
                errors.append(f"{path.name}: خطای دریافت گفتگوها: {exc}")
                continue

            total_found += len(dialogs)
            for dialog_index, dialog in enumerate(dialogs, 1):
                chat_id = dialog["id"]
                try:
                    await asyncio.wait_for(client.leave_group(chat_id), timeout=25)
                    left_count += 1
                except asyncio.CancelledError:
                    raise
                except Exception as exc:
                    is_owner = False
                    try:
                        full_group = await asyncio.wait_for(client.get_full_group(chat_id), timeout=15)
                        is_owner = as_int(getattr(full_group, "owner_id", 0)) == identity["id"]
                    except asyncio.CancelledError:
                        raise
                    except Exception:
                        pass
                    if is_owner:
                        owner_skipped += 1
                    else:
                        failed_count += 1
                        errors.append(f"{path.name} | {chat_id}: {exc}")

                if delay:
                    await asyncio.sleep(delay)
                if dialog_index % 10 == 0 or dialog_index == len(dialogs):
                    await safe_edit(
                        start,
                        f"🚪 سشن: {index} از {len(files)}\n"
                        f"📂 فایل: {path.name}\n"
                        f"📚 گفتگوهای این سشن: {dialog_index} از {len(dialogs)}\n"
                        f"✅ خروج موفق: {left_count}\n"
                        f"👑 مالک و ردشده: {owner_skipped}\n"
                        f"⚠️ خروج ناموفق: {failed_count}"
                    )
        finally:
            await safe_stop(client)

        await safe_edit(
            start,
            f"🚪 سشن بررسی‌شده: {index} از {len(files)}\n"
            f"✅ سشن سالم: {healthy_sessions}\n"
            f"❌ سشن خراب: {bad_sessions}\n"
            f"⚠️ خطای خواندن گفتگوها: {scan_failed_sessions}\n"
            f"📚 گروه/کانال پیدا شده: {total_found}\n"
            f"👑 مالک و خارج‌نشده: {owner_skipped}\n"
            f"🚶 خروج موفق: {left_count}\n"
            f"⚠️ خروج ناموفق: {failed_count}"
        )

    await safe_edit(
        start,
        "✅ عملیات خروج همگانی تمام شد.\n\n"
        f"📁 کل سشن‌ها: {len(files)}\n"
        f"✅ سشن سالم: {healthy_sessions}\n"
        f"❌ سشن خراب: {bad_sessions}\n"
        f"⚠️ خطای خواندن گفتگوها: {scan_failed_sessions}\n"
        f"📚 گروه و کانال پیدا شده: {total_found}\n"
        f"👑 مالک و خارج‌نشده: {owner_skipped}\n"
        f"🚶 خروج موفق: {left_count}\n"
        f"⚠️ خروج ناموفق: {failed_count}\n"
        "🗂 لیست لینک‌های ذخیره‌شده حذف نشد."
    )
    if errors:
        await send_text_report(
            message,
            "گزارش خطاهای خروج همگانی",
            errors,
            "leave_all_errors.txt"
        )


async def list_session_numbers(message):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ فایل سشنی وجود ندارد.")
        return
    lines = [f"{index}. {path.name}" for index, path in enumerate(files, 1)]
    await send_text_chunks(
        message,
        f"📱 شماره‌ها و فایل‌های سشن — تعداد: {len(files)}\n\n" + "\n".join(lines)
    )


async def scan_group_reports(message, owners_only=False):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    label = "مالکیت‌ها" if owners_only else "همه کانال‌ها و گروه‌ها"
    start = await message.reply(f"🔄 در حال بررسی {label}...")
    records = []
    errors = []
    healthy = 0
    bad = 0
    scanned_groups = 0
    seen = set()
    scan_delay = max(0.2, min(float(get_delay()), 2.0))

    for session_index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            try:
                identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
                healthy += 1
            except Exception as exc:
                bad += 1
                errors.append(f"{path.name}: {exc}")
                continue
            try:
                dialogs = await asyncio.wait_for(load_all_group_dialogs(client), timeout=180)
            except Exception as exc:
                errors.append(f"{path.name}: خطای لیست گفتگوها: {exc}")
                continue
            for dialog in dialogs:
                chat_id = dialog["id"]
                try:
                    full_group = await asyncio.wait_for(client.get_full_group(chat_id), timeout=45)
                    scanned_groups += 1
                    owner_id = as_int(getattr(full_group, "owner_id", 0))
                    is_owner = owner_id == identity["id"]
                    if owners_only and not is_owner:
                        continue
                    key = (chat_id, identity["id"] if owners_only else path.name)
                    if key in seen:
                        continue
                    seen.add(key)
                    records.append({
                        "chat_id": chat_id,
                        "title": str(iv(getattr(full_group, "title", "")) or "بدون عنوان"),
                        "username": str(iv(getattr(full_group, "username", "")) or "ندارد"),
                        "members": as_int(getattr(full_group, "members_count", 0)),
                        "group_type": group_type_name(getattr(full_group, "group_type", -1)),
                        "owner_id": owner_id,
                        "is_owner": is_owner,
                        "account_id": identity["id"],
                        "owner_phone": identity["phone"] if is_owner else "نامشخص",
                        "session_file": path.name
                    })
                except Exception as exc:
                    errors.append(f"{path.name} | {chat_id}: {exc}")
                await asyncio.sleep(scan_delay)
        finally:
            await safe_stop(client)
        await safe_edit(start, 
            f"🔄 بررسی سشن: {session_index} از {len(files)}\n"
            f"✅ سالم: {healthy}\n"
            f"❌ خراب: {bad}\n"
            f"📚 گروه بررسی‌شده: {scanned_groups}\n"
            f"📋 نتیجه: {len(records)}"
        )

    records.sort(key=lambda item: item["members"], reverse=True)
    if owners_only:
        lines = []
        for index, item in enumerate(records, 1):
            lines.append(
                f"{index}. {item['title']}\n"
                f"نوع: {item['group_type']}\n"
                f"آیدی کانال/گپ: {item['chat_id']}\n"
                f"آمار اعضا: {item['members']:,}\n"
                f"آیدی مالک: {item['owner_id']}\n"
                f"شماره مالک: {item['owner_phone']}\n"
                f"فایل مالک: {item['session_file']}\n"
                f"نام کاربری: {item['username']}\n"
                f"{'-' * 30}"
            )
        title = f"👑 گزارش مالکیت سشن‌ها — {len(records)} مورد"
        file_name = "owned_groups.txt"
    else:
        lines = []
        for index, item in enumerate(records, 1):
            lines.append(
                f"{index}. {item['title']}\n"
                f"نوع: {item['group_type']}\n"
                f"آیدی: {item['chat_id']}\n"
                f"آمار اعضا: {item['members']:,}\n"
                f"آیدی مالک: {item['owner_id'] or 'نامشخص'}\n"
                f"این سشن مالک است: {'بله' if item['is_owner'] else 'خیر'}\n"
                f"فایل سشن: {item['session_file']}\n"
                f"نام کاربری: {item['username']}\n"
                f"{'-' * 30}"
            )
        title = f"📚 گزارش همه کانال‌ها و گروه‌ها — {len(records)} عضویت"
        file_name = "all_groups.txt"

    await safe_edit(start, 
        f"✅ بررسی {label} تمام شد.\n\n"
        f"سشن سالم: {healthy}\n"
        f"سشن خراب: {bad}\n"
        f"گروه بررسی‌شده: {scanned_groups}\n"
        f"نتیجه: {len(records)}"
    )
    if lines:
        await send_text_report(message, title, lines, file_name)
    else:
        await message.reply(f"📭 هیچ موردی برای {label} پیدا نشد.")
    if errors:
        await send_text_report(message, f"خطاهای بررسی {label}", errors, f"{Path(file_name).stem}_errors.txt")


async def show_session_information(message, file_name):
    file_name = os.path.basename(file_name.strip())
    if not file_name.lower().endswith(".bale"):
        file_name += ".bale"
    path = SESSIONS_DIR / file_name
    if not path.exists():
        await message.reply("❌ فایل سشن پیدا نشد.")
        return
    start = await message.reply("🔄 در حال دریافت اطلاعات کامل سشن...")
    client = None
    try:
        client = Client(Dispatcher(), session_file=str(path))
        identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
        me = identity["me"]
        full = identity["full"]
        wallet = None
        try:
            wallet = await asyncio.wait_for(client.get_wallet(), timeout=45)
        except Exception:
            pass
        try:
            dialogs = await asyncio.wait_for(load_all_group_dialogs(client), timeout=180)
        except Exception:
            dialogs = []
        group_count = 0
        channel_count = 0
        supergroup_count = 0
        owned_count = 0
        for dialog in dialogs:
            try:
                group = await asyncio.wait_for(client.get_full_group(dialog["id"]), timeout=45)
                group_type = as_int(getattr(group, "group_type", -1))
                if group_type == as_int(GroupType.CHANNEL):
                    channel_count += 1
                elif group_type == as_int(GroupType.SUPERGROUP):
                    supergroup_count += 1
                else:
                    group_count += 1
                if as_int(getattr(group, "owner_id", 0)) == identity["id"]:
                    owned_count += 1
            except Exception:
                group_count += 1
            await asyncio.sleep(0.08)

        wallet_obj = getattr(wallet, "wallet", None) if wallet is not None else None
        balance = as_int(getattr(wallet_obj, "balance", 0))
        session_client_data = getattr(client, "me", None)
        verified = as_bool(getattr(getattr(me, "ex_info", None), "identified", False))
        full_verified = as_bool(getattr(getattr(full, "ex_info", None), "identified", False)) if full is not None else verified
        about = iv(getattr(full, "about", None)) if full else None
        languages = ", ".join(str(iv(item)) for item in (getattr(full, "languages", []) or [])) if full else "نامشخص"
        timezone_value = iv(getattr(full, "timezone", None)) if full else None
        text = (
            "ℹ️ اطلاعات کامل سشن\n\n"
            f"📁 فایل: {path.name}\n"
            f"📦 حجم فایل: {path.stat().st_size:,} بایت\n"
            f"🕒 آخرین تغییر فایل: {datetime.fromtimestamp(path.stat().st_mtime).strftime('%Y/%m/%d %H:%M:%S')}\n"
            f"✅ وضعیت: سالم\n\n"
            f"👤 نام: {identity['name']}\n"
            f"🆔 آیدی: {identity['id']}\n"
            f"📱 شماره: {identity['phone']}\n"
            f"🔗 نام کاربری: {identity['username'] or 'ندارد'}\n"
            f"📝 نام محلی: {getattr(me, 'local_name', None) or 'ندارد'}\n"
            f"🤖 ربات: {'بله' if as_bool(getattr(me, 'is_bot', False)) else 'خیر'}\n"
            f"✅ تاییدشده: {'بله' if full_verified else 'خیر'}\n"
            f"🗑 حذف‌شده: {'بله' if as_bool(getattr(me, 'is_deleted', False)) else 'خیر'}\n"
            f"📅 تاریخ ساخت حساب: {format_timestamp(getattr(me, 'created_at', getattr(full, 'created_at', 0) if full else 0))}\n"
            f"🧾 درباره: {about or 'ندارد'}\n"
            f"🌐 زبان‌ها: {languages or 'نامشخص'}\n"
            f"🕓 منطقه زمانی: {timezone_value or 'نامشخص'}\n"
            f"📨 اجازه دعوت: {'بله' if full and as_bool(getattr(full, 'allowed_invite', False)) else 'خیر/نامشخص'}\n\n"
            f"💰 موجودی: {balance:,} ریال ({balance // 10:,} تومان)\n"
            f"🏦 سطح کیف پول: {getattr(wallet_obj, 'level', 'نامشخص') if wallet_obj else 'نامشخص'}\n"
            f"🏪 حساب تجاری: {'بله' if wallet_obj and as_bool(getattr(wallet_obj, 'is_merchant', False)) else 'خیر'}\n"
            f"💳 کارت متصل: {mask_value(getattr(wallet_obj, 'pan', None)) if wallet_obj else 'نامشخص'}\n"
            f"🏧 حساب متصل: {mask_value(getattr(wallet_obj, 'account', None)) if wallet_obj else 'نامشخص'}\n\n"
            f"📚 کل کانال و گروه: {len(dialogs)}\n"
            f"👥 گروه: {group_count}\n"
            f"📢 کانال: {channel_count}\n"
            f"🧩 سوپرگروه: {supergroup_count}\n"
            f"👑 مالکیت‌ها: {owned_count}\n"
            f"🧩 App ID: {getattr(session_client_data, 'app_id', 'نامشخص') if session_client_data else 'نامشخص'}\n"
            f"🛰 سرویس: {getattr(session_client_data, 'service', 'نامشخص') if session_client_data else 'نامشخص'}\n\n"
            "🔒 توکن ورود، توکن کیف پول و داده خام سشن نمایش داده نمی‌شوند."
        )
        await safe_edit(start, text)
    except Exception as exc:
        await safe_edit(start, f"❌ سشن خراب است یا اطلاعات آن خوانده نشد:\n{exc}")
    finally:
        await safe_stop(client)


async def prepare_ownership_transfer(message, user_id, chat_id, new_owner_id):
    files = get_session_files()
    start = await message.reply("🔄 در حال پیدا کردن سشن مالک...")
    owner_data = None
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
            full_group = await asyncio.wait_for(client.get_full_group(chat_id), timeout=45)
            if as_int(getattr(full_group, "owner_id", 0)) == identity["id"]:
                owner_data = {
                    "path": path.name,
                    "owner_id": identity["id"],
                    "owner_phone": identity["phone"],
                    "chat_id": chat_id,
                    "new_owner_id": new_owner_id,
                    "title": str(iv(getattr(full_group, "title", "")) or "بدون عنوان"),
                    "members": as_int(getattr(full_group, "members_count", 0)),
                    "group_type": group_type_name(getattr(full_group, "group_type", -1))
                }
                break
        except Exception as exc:
            errors.append(f"{path.name}: {exc}")
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(start, f"🔄 سشن بررسی‌شده: {index} از {len(files)}")
    if owner_data is None:
        await safe_edit(start, "❌ بین سشن‌ها، مالک این کانال یا گپ پیدا نشد.")
        if errors:
            await send_text_report(message, "خطاهای یافتن مالک", errors, "owner_lookup_errors.txt")
        return
    user_data[user_id] = {"action": "confirm_transfer_ownership", **owner_data}
    keyboard = [["✅ تایید انتقال مالکیت"], ["❌ لغو انتقال مالکیت", "🔙 بازگشت"]]
    await safe_edit(start, 
        "⚠️ انتقال مالکیت یک عملیات حساس است.\n\n"
        f"عنوان: {owner_data['title']}\n"
        f"نوع: {owner_data['group_type']}\n"
        f"آیدی کانال/گپ: {chat_id}\n"
        f"آمار: {owner_data['members']:,}\n"
        f"مالک فعلی: {owner_data['owner_id']}\n"
        f"شماره مالک: {owner_data['owner_phone']}\n"
        f"سشن مالک: {owner_data['path']}\n"
        f"مالک جدید: {new_owner_id}\n\n"
        "فقط در صورت درست‌بودن همه اطلاعات، تأیید کنید.",
        ReplyKeyboard(*keyboard)
    )


async def execute_ownership_transfer(message, user_id):
    state = user_data.get(user_id, {})
    if state.get("action") != "confirm_transfer_ownership":
        await message.reply("❌ اطلاعات انتقال مالکیت پیدا نشد.")
        return
    path = SESSIONS_DIR / state["path"]
    client = None
    try:
        client = Client(Dispatcher(), session_file=str(path))
        identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
        full_group = await asyncio.wait_for(client.get_full_group(state["chat_id"]), timeout=45)
        if as_int(getattr(full_group, "owner_id", 0)) != identity["id"]:
            await message.reply("❌ این سشن دیگر مالک کانال یا گپ نیست.")
            return
        await asyncio.wait_for(
            client.transfer_group_ownership(state["chat_id"], state["new_owner_id"]),
            timeout=60
        )
        await message.reply(
            "✅ مالکیت با موفقیت منتقل شد.\n\n"
            f"آیدی کانال/گپ: {state['chat_id']}\n"
            f"مالک قبلی: {identity['id']}\n"
            f"مالک جدید: {state['new_owner_id']}"
        )
    except Exception as exc:
        await message.reply(
            "❌ انتقال مالکیت انجام نشد.\n"
            "مالک جدید معمولاً باید عضو کانال/گپ باشد و محدودیت امنیتی حساب نیز ممکن است مانع شود.\n\n"
            f"خطا: {exc}"
        )
    finally:
        user_data.pop(user_id, None)
        await safe_stop(client)


async def prepare_balance_collection(message, user_id, target_id):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    start_message = await message.reply("🔄 در حال محاسبه موجودی همه سشن‌ها...")
    eligible = []
    total = 0
    healthy = 0
    bad = 0
    wallet_failed = 0
    blocked_wallets = 0
    target_name = "تأییدنشده"
    target_verified = False
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            try:
                identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
                healthy += 1
            except Exception as exc:
                bad += 1
                errors.append(f"{path.name}: خطای سشن: {short_error(exc)}")
                continue

            if not target_verified:
                try:
                    target_user = await asyncio.wait_for(
                        client.load_user(target_id, ChatType.PRIVATE), timeout=45
                    )
                    target_name = str(getattr(target_user, "name", "") or "بدون نام")
                    target_verified = True
                except Exception as exc:
                    errors.append(f"{path.name}: تأیید مقصد ناموفق: {short_error(exc)}")

            if identity["id"] == target_id:
                continue

            try:
                wallet = await asyncio.wait_for(client.get_wallet(), timeout=45)
                balance = as_int(getattr(getattr(wallet, "wallet", None), "balance", 0))
            except Exception as exc:
                wallet_failed += 1
                decoded = short_error(exc)
                if "کیف پول مسدود" in decoded or "امکان فعالسازی وجود ندارد" in decoded:
                    blocked_wallets += 1
                errors.append(f"{path.name}: خطای کیف پول: {decoded}")
                continue

            if balance > 0:
                eligible.append({"file": path.name, "balance": balance, "sender_id": identity["id"]})
                total += balance
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(
                start_message,
                f"🔄 سشن بررسی‌شده: {index} از {len(files)}\n"
                f"✅ سشن سالم: {healthy}\n"
                f"❌ سشن خراب: {bad}\n"
                f"⚠️ خطای کیف پول: {wallet_failed}\n"
                f"🚫 کیف پول مسدود: {blocked_wallets}\n"
                f"💰 دارای موجودی: {len(eligible)}\n"
                f"مجموع: {total:,} ریال",
            )

    if not eligible:
        await safe_edit(
            start_message,
            "📭 هیچ موجودی قابل ارسالی پیدا نشد.\n\n"
            f"سشن سالم: {healthy}\nسشن خراب: {bad}\n"
            f"خطای کیف پول: {wallet_failed}\nکیف پول مسدود: {blocked_wallets}"
            + recent_error_preview(errors),
        )
        if errors:
            await send_text_report(message, "خطاهای بررسی موجودی", errors, "balance_scan_errors.txt")
        return

    user_data[user_id] = {
        "action": "confirm_balance_collection",
        "target_id": target_id,
        "target_name": target_name,
        "target_verified": target_verified,
        "eligible": eligible,
        "total": total,
    }
    keyboard = [["✅ تایید ارسال پاکت‌ها"], ["❌ لغو ارسال پاکت‌ها", "🔙 بازگشت"]]
    verification_note = "✅ مقصد از بله تأیید شد." if target_verified else "⚠️ نام مقصد خوانده نشد؛ آیدی عددی را دوباره بررسی کنید."
    await safe_edit(
        start_message,
        "⚠️ تأیید ارسال همه پاکت‌ها\n\n"
        f"مقصد: {target_name}\n"
        f"آیدی مقصد: {target_id}\n"
        f"تعداد سشن دارای موجودی: {len(eligible)}\n"
        f"مجموع: {total:,} ریال ({total // 10:,} تومان)\n"
        f"کیف پول مسدود/غیرقابل‌خواندن: {wallet_failed}\n\n"
        f"{verification_note}\n"
        "از هر سشن دارای موجودی یک پاکت خصوصی برای مقصد ارسال می‌شود.",
        ReplyKeyboard(*keyboard),
    )
    if errors:
        await send_text_report(message, "خطاهای بررسی موجودی", errors, "balance_scan_errors.txt")


async def execute_balance_collection(message, user_id):
    state = user_data.get(user_id, {})
    if state.get("action") != "confirm_balance_collection":
        await message.reply("❌ اطلاعات ارسال پاکت‌ها پیدا نشد.")
        return
    target_id = state["target_id"]
    items = state["eligible"]
    start = await message.reply("💰 ارسال پاکت‌ها شروع شد...")
    success = 0
    failed = 0
    sent_total = 0
    errors = []
    delay = get_delay()
    for index, item in enumerate(items, 1):
        path = SESSIONS_DIR / item["file"]
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
            if identity["id"] == target_id:
                continue
            wallet = await asyncio.wait_for(client.get_wallet(), timeout=45)
            balance = as_int(getattr(getattr(wallet, "wallet", None), "balance", 0))
            if balance <= 0:
                continue
            send_gift = getattr(client, "send_gift", None)
            if send_gift is None:
                raise RuntimeError("نسخه aiobale متد send_gift را ندارد")
            await asyncio.wait_for(
                send_gift(
                    chat_id=target_id,
                    chat_type=ChatType.PRIVATE,
                    amount=balance,
                    message="تجمیع موجودی سشن‌ها",
                    gift_count=1,
                    giving_type=GivingType.SAME,
                    show_amounts=True
                ),
                timeout=75
            )
            success += 1
            sent_total += balance
        except Exception as exc:
            failed += 1
            errors.append(f"{item['file']} | {item['balance']:,} ریال: {exc}")
        finally:
            await safe_stop(client)
        if delay:
            await asyncio.sleep(delay)
        await safe_edit(start, 
            f"💰 سشن پردازش‌شده: {index} از {len(items)}\n"
            f"✅ پاکت موفق: {success}\n"
            f"❌ ناموفق: {failed}\n"
            f"مبلغ ارسال‌شده: {sent_total:,} ریال"
        )
    user_data.pop(user_id, None)
    await safe_edit(start, 
        "✅ عملیات ارسال پاکت‌ها تمام شد.\n\n"
        f"مقصد: {state['target_name']}\n"
        f"آیدی مقصد: {target_id}\n"
        f"پاکت موفق: {success}\n"
        f"پاکت ناموفق: {failed}\n"
        f"مجموع ارسال‌شده: {sent_total:,} ریال ({sent_total // 10:,} تومان)\n\n"
        "حساب مقصد باید پاکت‌های دریافتی را باز کند."
    )
    if errors:
        await send_text_report(message, "خطاهای ارسال پاکت‌ها", errors, "gift_send_errors.txt")


# ---------- Session Messaging Features ----------

BROADCAST_MIN_DELAY = 2.0


def installed_package_version(package_name):
    try:
        return importlib_metadata.version(package_name)
    except Exception:
        return "unknown"


def write_debug_log(context, exc=None, details=None):
    stamp = datetime.now().strftime("%Y%m%d")
    path = LOG_DIR / f"runtime_{stamp}.log"
    lines = [f"[{datetime.now().isoformat(timespec='seconds')}] {context}"]
    if details:
        lines.append(str(details))
    if exc is not None:
        lines.append(f"{type(exc).__name__}: {exc}")
        lines.append("".join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
    try:
        with path.open("a", encoding="utf-8") as handle:
            handle.write("\n".join(lines) + "\n" + ("-" * 72) + "\n")
    except Exception:
        pass


def short_error(exc):
    value = f"{type(exc).__name__}: {exc}".strip()
    try:
        value = unquote(value)
    except Exception:
        pass
    return value[:500] if value else type(exc).__name__


def recent_error_preview(errors, limit=3):
    if not errors:
        return ""
    unique = []
    for item in errors:
        item = str(item)
        if item not in unique:
            unique.append(item)
        if len(unique) >= limit:
            break
    return "\n\nنمونه خطاها:\n" + "\n".join(f"• {item[:240]}" for item in unique)



def extract_aiobale_message_text(message):
    direct = getattr(message, "text", None)
    if direct not in (None, ""):
        return str(iv(direct) or "")
    content = getattr(message, "content", None)
    if content is None:
        return ""
    text_obj = getattr(content, "text", None)
    if text_obj is not None:
        return str(iv(getattr(text_obj, "value", text_obj)) or "")
    bot_message = getattr(content, "bot_message", None)
    nested = getattr(bot_message, "message", None) if bot_message is not None else None
    nested_text = getattr(nested, "text", None) if nested is not None else None
    if nested_text is not None:
        return str(iv(getattr(nested_text, "value", nested_text)) or "")
    return ""


async def message_exists_in_recent_history(client, chat_id, chat_type, text, started_ms):
    try:
        messages = await asyncio.wait_for(
            client.load_history(chat_id=int(chat_id), chat_type=chat_type, limit=20),
            timeout=35,
        )
    except Exception:
        return False
    expected = str(text or "").strip()
    for item in messages or []:
        if extract_aiobale_message_text(item).strip() != expected:
            continue
        date_value = as_int(getattr(item, "date", 0), 0)
        if date_value and date_value < 10_000_000_000:
            date_value *= 1000
        if not date_value or date_value >= started_ms - 120_000:
            return True
    return False


async def send_message_verified(client, text, chat_id, chat_type, timeout=45):
    started_ms = int(time.time() * 1000)
    try:
        result = await asyncio.wait_for(
            client.send_message(text=str(text), chat_id=int(chat_id), chat_type=chat_type),
            timeout=timeout,
        )
        return True, "پاسخ مستقیم سرویس", result, None
    except asyncio.CancelledError:
        raise
    except Exception as exc:
        if await message_exists_in_recent_history(client, chat_id, chat_type, text, started_ms):
            return True, "تأیید از تاریخچه پس از خطای پاسخ", None, exc
        return False, "ناموفق", None, exc


async def get_phone_from_session_file(message, file_name):
    safe_name = os.path.basename(str(file_name or "").strip())
    if not safe_name.lower().endswith(".bale"):
        safe_name += ".bale"
    path = SESSIONS_DIR / safe_name
    if not path.exists() or not path.is_file():
        await message.reply("❌ فایل سشن پیدا نشد.")
        return
    filename_phone = clean_phone("", path.name)
    client = None
    try:
        client = Client(Dispatcher(), session_file=str(path))
        identity = await asyncio.wait_for(get_account_identity(client, path), timeout=45)
        phone = identity.get("phone") or filename_phone
        if phone == "نامشخص":
            phone = filename_phone
        await message.reply(
            "📞 شماره سشن\n\n"
            f"📁 فایل: {path.name}\n"
            f"📱 شماره: {phone}\n"
            f"👤 نام: {identity.get('name', 'نامشخص')}\n"
            f"🆔 آیدی: {identity.get('id', 'نامشخص')}"
        )
    except Exception as exc:
        if filename_phone != "نامشخص":
            await message.reply(
                "⚠️ اطلاعات حساب از بله خوانده نشد، اما شماره از نام فایل استخراج شد.\n\n"
                f"📁 فایل: {path.name}\n📱 شماره: {filename_phone}\n"
                f"خطا: {short_error(exc)}"
            )
        else:
            await message.reply(f"❌ شماره از نام فایل یا خود سشن قابل استخراج نبود.\n{short_error(exc)}")
    finally:
        await safe_stop(client)


async def bulk_change_session_names(message, new_name):
    new_name = str(new_name or "").strip()
    if not new_name:
        await message.reply("⚠️ نام جدید خالی است.")
        return
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    progress = await message.reply("✏️ تغییر نام همه حساب‌ها شروع شد...")
    success = failed = 0
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)
            edit_error = None
            try:
                await asyncio.wait_for(client.edit_name(new_name), timeout=45)
            except Exception as exc:
                edit_error = exc
            verified = False
            try:
                me = await asyncio.wait_for(client.get_me(), timeout=35)
                verified = str(getattr(me, "name", "") or "").strip() == new_name
            except Exception:
                verified = edit_error is None
            if not verified:
                raise edit_error or RuntimeError("نام جدید پس از ویرایش تأیید نشد")
            success += 1
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            failed += 1
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("bulk_rename", exc, error)
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(progress, f"✏️ بررسی‌شده: {index} از {len(files)}\n✅ موفق: {success}\n❌ ناموفق: {failed}" + recent_error_preview(errors))
        await asyncio.sleep(min(max(float(get_delay()), 0.2), 3.0))
    await safe_edit(progress, f"✅ تغییر نام همه حساب‌ها تمام شد.\n\nنام جدید: {new_name}\nموفق: {success}\nناموفق: {failed}" + recent_error_preview(errors))
    if errors:
        await send_text_report(message, "خطاهای تغییر نام همه سشن‌ها", errors, "bulk_rename_errors.txt")


async def bulk_clear_session_bios(message):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    progress = await message.reply("🧹 پاک‌کردن بیوی همه حساب‌ها شروع شد...")
    success = failed = 0
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)
            edit_error = None
            try:
                await asyncio.wait_for(client.edit_about(""), timeout=45)
            except Exception as exc:
                edit_error = exc
            verified = False
            try:
                full = await asyncio.wait_for(client.get_full_me(), timeout=45)
                about = str(iv(getattr(full, "about", "")) or "").strip()
                verified = about == ""
            except Exception:
                verified = edit_error is None
            if not verified:
                raise edit_error or RuntimeError("خالی‌شدن بیو پس از ویرایش تأیید نشد")
            success += 1
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            failed += 1
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("bulk_clear_bio", exc, error)
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(progress, f"🧹 بررسی‌شده: {index} از {len(files)}\n✅ موفق: {success}\n❌ ناموفق: {failed}" + recent_error_preview(errors))
        await asyncio.sleep(min(max(float(get_delay()), 0.2), 3.0))
    await safe_edit(progress, f"✅ پاک‌کردن بیوی همه حساب‌ها تمام شد.\n\nموفق: {success}\nناموفق: {failed}" + recent_error_preview(errors))
    if errors:
        await send_text_report(message, "خطاهای پاک‌کردن بیوی همه سشن‌ها", errors, "bulk_clear_bio_errors.txt")


async def send_one_allowed_message(message, chat_id, chat_type, body, delay):
    chat_id = int(chat_id)
    body = str(body or "").strip()
    if chat_type in (ChatType.PRIVATE, ChatType.BOT):
        allowed = chat_id in get_allowed_private_ids()
        label = "پیوی"
    else:
        allowed = chat_id in get_allowed_chat_ids()
        label = "گروه/کانال"
    if not allowed:
        await message.reply(
            f"⛔ آیدی {chat_id} در فهرست مجاز {label} نیست؛ پیام ارسال نشد."
        )
        return
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    progress = await message.reply("📨 در حال ارسال یک پیام با اولین سشن قابل استفاده...")
    errors = []
    if delay:
        await asyncio.sleep(delay)
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)
            resolved_type = chat_type
            if chat_type in (ChatType.GROUP, ChatType.CHANNEL, ChatType.SUPER_GROUP):
                resolved_type = await resolve_group_chat_type(client, chat_id, chat_type)
            else:
                resolved_type = await resolve_private_chat_type(client, chat_id)
            ok, verification, _, send_error = await send_message_verified(
                client, body, chat_id, resolved_type
            )
            if not ok:
                raise send_error or RuntimeError("ارسال پیام تأیید نشد")
            note = ""
            if send_error is not None:
                note = f"\nℹ️ پاسخ کتابخانه خطا داشت، ولی پیام در تاریخچه مقصد دیده شد: {short_error(send_error)}"
            await safe_edit(
                progress,
                "✅ پیام ارسال و تأیید شد.\n\n"
                f"آیدی: {chat_id}\nنوع: {chat_type_label(resolved_type)}\n"
                f"سشن: {path.name}\nروش تأیید: {verification}" + note,
            )
            return
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("single_send", exc, error)
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(progress, f"📨 سشن بررسی‌شده: {index} از {len(files)}" + recent_error_preview(errors))
    await safe_edit(progress, "❌ هیچ سشنی نتوانست ارسال پیام را تأیید کند." + recent_error_preview(errors))
    if errors:
        await send_text_report(message, "خطاهای ارسال پیام", errors, "single_send_errors.txt")


# ------- NEW: Repeated message sending with unlimited option -------
async def send_repeated_messages(message, chat_id, chat_type, session_count, repeat_count, body, delay):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return

    # Select sessions (use all if session_count > len(files))
    selected = files[:session_count] if session_count > 0 else files
    if not selected:
        await message.reply("⚠️ تعداد سشن انتخاب‌شده صفر است.")
        return

    total_sessions = len(selected)
    progress = await message.reply("📨 شروع ارسال پیام‌های تکراری...")
    errors = []
    sent_count = 0
    repeat = 0
    unlimited = (str(repeat_count).strip().lower() == "نامحدود")
    max_repeats = None if unlimited else int(repeat_count)

    try:
        while unlimited or (max_repeats is not None and repeat < max_repeats):
            # Check for cancellation flag
            if user_data.get(message.author.id, {}).get("cancel", False):
                await message.reply("⏹ عملیات توسط کاربر لغو شد.")
                return

            for idx, path in enumerate(selected, 1):
                # Check cancel flag inside loop
                if user_data.get(message.author.id, {}).get("cancel", False):
                    await message.reply("⏹ عملیات توسط کاربر لغو شد.")
                    return

                client = None
                try:
                    client = Client(Dispatcher(), session_file=str(path))
                    await asyncio.wait_for(client.get_me(), timeout=35)
                    resolved_type = chat_type
                    if chat_type in (ChatType.GROUP, ChatType.CHANNEL, ChatType.SUPER_GROUP):
                        resolved_type = await resolve_group_chat_type(client, chat_id, chat_type)
                    else:
                        resolved_type = await resolve_private_chat_type(client, chat_id)

                    ok, verification, _, send_error = await send_message_verified(
                        client, body, chat_id, resolved_type
                    )
                    if not ok:
                        raise send_error or RuntimeError("ارسال تأیید نشد")
                    sent_count += 1
                except asyncio.CancelledError:
                    raise
                except Exception as exc:
                    error = f"{path.name}: {short_error(exc)}"
                    errors.append(error)
                    write_debug_log("repeat_send", exc, error)
                finally:
                    await safe_stop(client)

                # Update progress
                if (idx % 5 == 0) or (idx == total_sessions):
                    await safe_edit(progress,
                        f"📨 تکرار {repeat+1} – سشن {idx}/{total_sessions}\n"
                        f"✅ ارسال موفق: {sent_count}\n"
                        f"⚠️ خطاها: {len(errors)}"
                        + recent_error_preview(errors)
                    )

                if delay:
                    await asyncio.sleep(delay)

            repeat += 1
            if max_repeats is not None and repeat >= max_repeats:
                break

        await safe_edit(progress,
            "✅ عملیات ارسال تکراری تمام شد.\n\n"
            f"تعداد تکرار: {repeat}\n"
            f"تعداد سشن استفاده‌شده: {total_sessions}\n"
            f"مجموع پیام‌های ارسال‌شده: {sent_count}\n"
            f"خطاها: {len(errors)}"
            + recent_error_preview(errors)
        )
        if errors:
            await send_text_report(message, "خطاهای ارسال تکراری", errors, "repeat_send_errors.txt")
    except asyncio.CancelledError:
        await safe_edit(progress, "⏹ عملیات ارسال تکراری متوقف شد.")
        raise
    finally:
        # Clear cancellation flag
        user_data.pop(message.author.id, None)


# ------- NEW: Smart report with bait message -------
async def smart_report_with_bait(message, chat_id, chat_type, bait_text, reason):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return

    progress = await message.reply("📤 ارسال بیت و گزارش هوشمند...")
    errors = []

    for path in files:
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)

            # Send bait message
            resolved_type = chat_type
            if chat_type in (ChatType.GROUP, ChatType.CHANNEL, ChatType.SUPER_GROUP):
                resolved_type = await resolve_group_chat_type(client, chat_id, chat_type)
            else:
                resolved_type = await resolve_private_chat_type(client, chat_id)

            ok, verification, _, send_error = await send_message_verified(
                client, bait_text, chat_id, resolved_type
            )
            if not ok:
                raise send_error or RuntimeError("ارسال بیت تأیید نشد")

            # Send report
            await asyncio.wait_for(
                client.report_chat(chat_id=chat_id, chat_type=resolved_type, reason=reason),
                timeout=45
            )

            await safe_edit(progress,
                "✅ گزارش هوشمند با موفقیت انجام شد.\n\n"
                f"نوع: {chat_type_label(resolved_type)}\n"
                f"آیدی: {chat_id}\n"
                f"سشن: {path.name}\n"
                f"دلیل: {reason}"
            )
            return
        except Exception as exc:
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("smart_report_bait", exc, error)
        finally:
            await safe_stop(client)

    await safe_edit(progress,
        "❌ هیچ سشنی نتوانست گزارش هوشمند را کامل کند."
        + recent_error_preview(errors)
    )
    if errors:
        await send_text_report(message, "خطاهای گزارش هوشمند", errors, "smart_report_errors.txt")


# ---------- End new features ----------

def parse_composite_int(value, default=0):
    value = iv(value)
    if isinstance(value, int):
        return value
    raw = str(value or "").strip()
    if not raw:
        return default
    # Balethon chat ids are encoded as "id|type" and message ids as "rid:date".
    raw = raw.split("|", 1)[0].split(":", 1)[0].strip()
    try:
        return int(raw)
    except Exception:
        return default


def chat_type_label(chat_type):
    mapping = {
        as_int(ChatType.PRIVATE): "خصوصی",
        as_int(ChatType.BOT): "ربات",
        as_int(ChatType.CHANNEL): "کانال",
        as_int(ChatType.GROUP): "گروه",
        as_int(ChatType.SUPER_GROUP): "سوپرگروه",
    }
    return mapping.get(as_int(chat_type, -1), str(iv(chat_type)))


def parse_chat_type_code(value):
    normalized = convert_to_english_numbers(value).strip().lower()
    mapping = {
        "1": ChatType.PRIVATE, "private": ChatType.PRIVATE, "خصوصی": ChatType.PRIVATE,
        "2": ChatType.CHANNEL, "channel": ChatType.CHANNEL, "کانال": ChatType.CHANNEL,
        "3": ChatType.GROUP, "group": ChatType.GROUP, "گروه": ChatType.GROUP, "گپ": ChatType.GROUP,
        "4": ChatType.BOT, "bot": ChatType.BOT, "ربات": ChatType.BOT,
        "5": ChatType.SUPER_GROUP, "supergroup": ChatType.SUPER_GROUP, "سوپرگروه": ChatType.SUPER_GROUP,
    }
    return mapping.get(normalized)


def infer_forward_chat_type(forward_chat):
    raw_type = getattr(forward_chat, "type", None)
    numeric_type = as_int(raw_type, -999)
    valid_values = {
        as_int(ChatType.PRIVATE): ChatType.PRIVATE,
        as_int(ChatType.GROUP): ChatType.GROUP,
        as_int(ChatType.CHANNEL): ChatType.CHANNEL,
        as_int(ChatType.BOT): ChatType.BOT,
        as_int(ChatType.SUPER_GROUP): ChatType.SUPER_GROUP,
    }
    if numeric_type in valid_values:
        return valid_values[numeric_type]
    type_text = str(iv(raw_type) or "").strip().lower()
    if "private" in type_text or "user" in type_text or "خصوص" in type_text:
        return ChatType.PRIVATE
    if "channel" in type_text or "کانال" in type_text:
        return ChatType.CHANNEL
    if "super" in type_text or "سوپر" in type_text:
        return ChatType.SUPER_GROUP
    encoded = str(getattr(forward_chat, "id", "") or "")
    if "|" in encoded:
        suffix = encoded.rsplit("|", 1)[-1]
        if suffix == "1":
            return ChatType.PRIVATE
        if suffix == "3":
            return ChatType.CHANNEL
    return ChatType.GROUP


def is_forwarded_message(message):
    origin = getattr(message, "forward_origin", None)
    return bool(
        origin
        or getattr(message, "forward_from_chat", None)
        or getattr(message, "forward_from", None)
        or getattr(message, "forward_from_message_id", None)
        or getattr(message, "forward_date", None)
    )


def get_forward_chat_target(message):
    origin = getattr(message, "forward_origin", None)
    if origin is not None:
        origin_chat = getattr(origin, "chat", None)
        if origin_chat is not None:
            chat_id = parse_composite_int(getattr(origin_chat, "id", 0))
            if chat_id:
                return chat_id, infer_forward_chat_type(origin_chat)
        sender_user = getattr(origin, "sender_user", None)
        if sender_user is not None:
            chat_id = parse_composite_int(getattr(sender_user, "id", 0))
            if chat_id:
                return chat_id, ChatType.PRIVATE

    forward_chat = getattr(message, "forward_from_chat", None)
    if forward_chat is not None:
        chat_id = parse_composite_int(getattr(forward_chat, "id", 0))
        if not chat_id:
            raise ValueError("آیدی چت مبدأ از فوروارد استخراج نشد")
        return chat_id, infer_forward_chat_type(forward_chat)

    forward_user = getattr(message, "forward_from", None)
    if forward_user is not None:
        chat_id = parse_composite_int(getattr(forward_user, "id", 0))
        if not chat_id:
            raise ValueError("آیدی کاربر مبدأ از فوروارد استخراج نشد")
        return chat_id, ChatType.PRIVATE

    raise ValueError("پیام فورواردی معتبر نیست یا مبدأ آن مخفی است")


def get_forward_target(message):
    chat_id, chat_type = get_forward_chat_target(message)
    origin = getattr(message, "forward_origin", None)
    message_id = parse_composite_int(getattr(origin, "message_id", 0)) if origin else 0
    if not message_id:
        message_id = parse_composite_int(getattr(message, "forward_from_message_id", 0))
    if not message_id:
        raise ValueError("شناسه پیام اصلی در فوروارد وجود ندارد؛ فوروارد باید قابل‌انتساب باشد")
    return chat_id, message_id, chat_type


async def resolve_group_chat_type(client, chat_id, fallback=ChatType.GROUP):
    try:
        full_group = await asyncio.wait_for(client.get_full_group(int(chat_id)), timeout=25)
        group_type = as_int(getattr(full_group, "group_type", -1), -1)
        if group_type == as_int(GroupType.CHANNEL, -10):
            return ChatType.CHANNEL
        if group_type == as_int(GroupType.SUPERGROUP, -11):
            return ChatType.SUPER_GROUP
        return ChatType.GROUP
    except Exception:
        return fallback


async def resolve_private_chat_type(client, chat_id):
    try:
        user = await asyncio.wait_for(client.load_user(int(chat_id), ChatType.PRIVATE), timeout=25)
        if as_bool(getattr(user, "is_bot", False)) or as_bool(getattr(user, "bot", False)):
            return ChatType.BOT
    except Exception:
        pass
    return ChatType.PRIVATE


async def find_message_in_history(client, chat_id, chat_type, message_id):
    offset_date = -1
    seen_offsets = set()
    for _ in range(12):
        messages = await asyncio.wait_for(
            client.load_history(chat_id=chat_id, chat_type=chat_type, limit=50, offset_date=offset_date),
            timeout=35,
        )
        if not messages:
            break
        for item in messages:
            if parse_composite_int(getattr(item, "message_id", 0)) == int(message_id):
                return item
        dates = [as_int(getattr(item, "date", 0)) for item in messages]
        dates = [value for value in dates if value > 0]
        if not dates:
            break
        next_offset = min(dates) - 1
        if next_offset in seen_offsets or (offset_date != -1 and next_offset >= offset_date):
            break
        seen_offsets.add(next_offset)
        offset_date = next_offset
        if len(messages) < 50:
            break
    return None


async def load_all_private_dialogs(client):
    private_ids = []
    private_seen = set()
    offset_date = -1
    seen_offsets = set()
    seen_pages = set()
    preferred_limit = 40
    for page_index in range(1000):
        dialogs = None
        last_error = None
        trial_limits = []
        current_limit = preferred_limit
        while current_limit >= 1:
            if current_limit not in trial_limits:
                trial_limits.append(current_limit)
            if current_limit == 1:
                break
            current_limit = max(1, current_limit // 2)
        for page_limit in trial_limits:
            try:
                dialogs = await asyncio.wait_for(
                    client.load_dialogs(limit=page_limit, offset_date=offset_date, exclude_pinned=page_index > 0),
                    timeout=25,
                )
                preferred_limit = page_limit
                break
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                last_error = exc
                error_text = short_error(exc).lower()
                if not any(token in error_text for token in ("validation", "peerdata", "none is not an allowed value")):
                    raise
        if dialogs is None:
            if private_ids:
                break
            if last_error is not None:
                raise last_error
            break
        if not dialogs:
            break
        page_signature = []
        page_dates = []
        for dialog in dialogs:
            peer = getattr(dialog, "peer", None)
            if peer is None:
                continue
            peer_type = as_int(getattr(peer, "type", 0))
            peer_id = as_int(getattr(peer, "id", 0))
            sort_date = as_int(getattr(dialog, "sort_date", 0))
            page_signature.append((peer_type, peer_id, sort_date))
            if peer_type == as_int(PeerType.PRIVATE) and peer_id and peer_id not in private_seen:
                private_seen.add(peer_id)
                private_ids.append(peer_id)
            if sort_date > 0:
                page_dates.append(sort_date)
        signature = tuple(page_signature)
        if signature in seen_pages:
            break
        seen_pages.add(signature)
        if not page_dates:
            break
        next_offset = min(page_dates) - 1
        if next_offset in seen_offsets or (offset_date != -1 and next_offset >= offset_date):
            break
        seen_offsets.add(next_offset)
        offset_date = next_offset
        if len(dialogs) < preferred_limit:
            break
    return private_ids


async def send_to_all_private(message, user_id, text):
    text = str(text or "").strip()
    targets = sorted(get_allowed_private_ids())
    if not targets:
        await message.reply(
            "⚠️ فهرست پیوی‌های مجاز خالی است. برای جلوگیری از ارسال ناخواسته، پیام ارسال نشد.\n"
            "از تنظیمات، «➕ افزودن پیوی مجاز» را بزنید."
        )
        return
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    progress = await message.reply("📨 ارسال به پیوی‌های مجاز شروع شد...")
    sent = failed = healthy = session_failed = 0
    errors = []
    used_sessions = set()
    for target_index, chat_id in enumerate(targets, 1):
        target_sent = False
        for path in files:
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                await asyncio.wait_for(client.get_me(), timeout=35)
                healthy += 1
                chat_type = await resolve_private_chat_type(client, chat_id)
                ok, verification, _, send_error = await send_message_verified(
                    client, text, chat_id, chat_type
                )
                if not ok:
                    raise send_error or RuntimeError("ارسال پیام در تاریخچه تأیید نشد")
                if send_error is not None:
                    errors.append(
                        f"{path.name} -> {chat_id}: ارسال در تاریخچه تأیید شد؛ خطای پاسخ: {short_error(send_error)}"
                    )
                sent += 1
                used_sessions.add(path.name)
                target_sent = True
                break
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                error = f"{path.name} -> {chat_id}: {short_error(exc)}"
                errors.append(error)
                write_debug_log("private_send", exc, error)
                session_failed += 1
            finally:
                await safe_stop(client)
            await asyncio.sleep(BROADCAST_MIN_DELAY)
        if not target_sent:
            failed += 1
        await safe_edit(
            progress,
            f"📨 مقصد: {target_index} از {len(targets)}\n"
            f"✅ ارسال موفق: {sent}\n❌ مقصد ناموفق: {failed}\n"
            f"📱 سشن استفاده‌شده: {len(used_sessions)}\n⚠️ تلاش ناموفق: {session_failed}"
            + recent_error_preview(errors),
        )
    await safe_edit(
        progress,
        "✅ ارسال به پیوی‌های مجاز تمام شد.\n\n"
        f"مقصد مجاز: {len(targets)}\nموفق: {sent}\nناموفق: {failed}\n"
        f"سشن استفاده‌شده: {len(used_sessions)}\nتلاش ناموفق: {session_failed}"
        + recent_error_preview(errors),
    )
    if errors:
        await send_text_report(message, "خطاهای ارسال پیوی مجاز", errors, "send_private_errors.txt")


async def send_to_all_groups(message, user_id, text):
    text = str(text or "").strip()
    targets = sorted(get_allowed_chat_ids())
    if not targets:
        await message.reply(
            "⚠️ فهرست گروه‌ها/کانال‌های مجاز خالی است. ابتدا با دستور «عضو شو» مقصد مجاز ثبت کنید."
        )
        return
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی وجود ندارد.")
        return
    progress = await message.reply("📨 ارسال به گروه‌ها و کانال‌های مجاز شروع شد...")
    sent = failed = attempts_failed = 0
    used_sessions = set()
    errors = []
    for target_index, chat_id in enumerate(targets, 1):
        target_sent = False
        for path in files:
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                await asyncio.wait_for(client.get_me(), timeout=35)
                chat_type = await resolve_group_chat_type(client, chat_id)
                ok, verification, _, send_error = await send_message_verified(
                    client, text, chat_id, chat_type
                )
                if not ok:
                    raise send_error or RuntimeError("ارسال پیام در تاریخچه تأیید نشد")
                if send_error is not None:
                    errors.append(
                        f"{path.name} -> {chat_id}: ارسال در تاریخچه تأیید شد؛ خطای پاسخ: {short_error(send_error)}"
                    )
                sent += 1
                used_sessions.add(path.name)
                target_sent = True
                break
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                attempts_failed += 1
                error = f"{path.name} -> {chat_id}: {short_error(exc)}"
                errors.append(error)
                write_debug_log("group_send", exc, error)
            finally:
                await safe_stop(client)
            await asyncio.sleep(BROADCAST_MIN_DELAY)
        if not target_sent:
            failed += 1
        await safe_edit(
            progress,
            f"📨 مقصد: {target_index} از {len(targets)}\n✅ موفق: {sent}\n❌ ناموفق: {failed}\n"
            f"📱 سشن استفاده‌شده: {len(used_sessions)}\n⚠️ تلاش ناموفق: {attempts_failed}"
            + recent_error_preview(errors),
        )
    await safe_edit(
        progress,
        "✅ ارسال به مقصدهای مجاز تمام شد.\n\n"
        f"مقصد مجاز: {len(targets)}\nموفق: {sent}\nناموفق: {failed}\n"
        f"سشن استفاده‌شده: {len(used_sessions)}\nتلاش ناموفق: {attempts_failed}"
        + recent_error_preview(errors),
    )
    if errors:
        await send_text_report(message, "خطاهای ارسال گروهی مجاز", errors, "send_group_errors.txt")


async def reaction_flow_pick(message, user_id):
    keyboard, row = [], []
    for emoji in reactions:
        row.append(emoji)
        if len(row) == 4:
            keyboard.append(row); row = []
    if row:
        keyboard.append(row)
    keyboard.append(["🔙 بازگشت"])
    user_data[user_id] = {"action": "reaction_pick"}
    await message.reply(
        "👁 واکنش را انتخاب کنید؛ سپس پیام اصلی را فوروارد کنید.\n"
        "واکنش با اولین سشن سالم، عضو مقصد و دارای دسترسی ثبت می‌شود.",
        ReplyKeyboard(*keyboard),
    )


async def reaction_pick_handle(message, user_id, text):
    if text not in reactions:
        await message.reply("⚠️ یکی از واکنش‌های صفحه‌کلید را انتخاب کنید.")
        return
    user_data[user_id] = {"action": "reaction_forward", "reaction": text}
    await message.reply(f"✅ واکنش {text} انتخاب شد. حالا پیام را فوروارد کنید.", ReplyKeyboard(*MAIN_KEYBOARD))


def peer_type_for_chat(chat_type):
    if chat_type in (ChatType.PRIVATE, ChatType.BOT):
        return PeerType.PRIVATE
    return PeerType.GROUP


async def set_reaction_compat(client, reaction, target_message, chat_id, chat_type):
    # aiobale 0.1.5 passes ChatType directly as Peer.type inside Client.set_reaction.
    # That only works accidentally for GROUP=2. CHANNEL=3 and SUPER_GROUP=5 must
    # be normalized to PeerType.GROUP=2 before MessageSetReaction is sent.
    peer = Peer(id=int(chat_id), type=peer_type_for_chat(chat_type))
    method = MessageSetReaction(
        peer=peer,
        message_id=int(getattr(target_message, "message_id")),
        date=getattr(target_message, "date"),
        emojy=reaction,
    )
    return await client(method)


async def apply_reaction_all_sessions(message, reaction, chat_id, message_id, chat_type):
    files = get_session_files()
    if not files:
        await message.reply("📭 هیچ سشنی برای ثبت واکنش وجود ندارد.")
        return

    progress = await message.reply("👁 در حال پیدا کردن یک سشن عضو و دارای دسترسی...")
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)
            if chat_type in (ChatType.GROUP, ChatType.CHANNEL, ChatType.SUPER_GROUP):
                resolved_type = await resolve_group_chat_type(client, chat_id, chat_type)
            else:
                resolved_type = await resolve_private_chat_type(client, chat_id)

            target_message = await find_message_in_history(
                client, chat_id, resolved_type, message_id
            )
            if target_message is None:
                raise LookupError(
                    "پیام اصلی در تاریخچه این سشن پیدا نشد؛ سشن احتمالاً عضو نیست یا پیام قدیمی است"
                )

            reaction_method = "واکنش ایموجی"
            try:
                await asyncio.wait_for(
                    set_reaction_compat(
                        client, reaction, target_message, chat_id, resolved_type
                    ),
                    timeout=45,
                )
            except Exception as reaction_exc:
                # Bale magazine/channel posts may expose an upvote instead of emoji reactions.
                # The official aiobale example uses upvote_post for forwarded magazine posts.
                if resolved_type == ChatType.CHANNEL and reaction == "👍":
                    try:
                        await asyncio.wait_for(
                            client.upvote_post(target_message), timeout=45
                        )
                        reaction_method = "پسند پست کانال"
                    except Exception:
                        raise reaction_exc
                else:
                    raise

            await safe_edit(
                progress,
                "✅ واکنش واقعاً ثبت شد.\n\n"
                f"واکنش: {reaction}\n"
                f"نوع مقصد: {chat_type_label(resolved_type)}\n"
                f"روش: {reaction_method}\n"
                f"سشن: {path.name}",
            )
            return
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("reaction", exc, error)
        finally:
            await safe_stop(client)

        if should_update(index, len(files)):
            await safe_edit(
                progress,
                f"👁 سشن بررسی‌شده: {index} از {len(files)}"
                + recent_error_preview(errors),
            )

    await safe_edit(
        progress,
        "❌ هیچ سشن دارای دسترسی نتوانست واکنش را ثبت کند."
        + recent_error_preview(errors),
    )
    if errors:
        await send_text_report(
            message, "خطاهای واکنش", errors, "reaction_errors.txt"
        )


async def reaction_forward_handle(message, user_id):
    state = user_data.get(user_id, {})
    reaction = state.get("reaction") if isinstance(state, dict) else None
    if not reaction:
        await message.reply("❌ واکنش انتخاب نشده است.")
        return
    try:
        chat_id, message_id, chat_type = get_forward_target(message)
    except ValueError as exc:
        await message.reply(f"❌ {exc}")
        return
    user_data.pop(user_id, None)
    await run_exclusive(message, "ثبت واکنش", apply_reaction_all_sessions, message, reaction, chat_id, message_id, chat_type)


async def mark_seen_all_sessions(message, chat_id, chat_type):
    files = get_session_files()
    progress = await message.reply("🔁 در حال پیدا کردن یک سشن دارای دسترسی...")
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)
            if chat_type in (ChatType.GROUP, ChatType.CHANNEL, ChatType.SUPER_GROUP):
                resolved_type = await resolve_group_chat_type(client, chat_id, chat_type)
            else:
                resolved_type = await resolve_private_chat_type(client, chat_id)
            await asyncio.wait_for(client.seen_chat(chat_id=chat_id, chat_type=resolved_type), timeout=35)
            await safe_edit(
                progress,
                "✅ چت خوانده‌شده علامت خورد.\n\n"
                f"نوع: {chat_type_label(resolved_type)}\nسشن: {path.name}",
            )
            return
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("seen", exc, error)
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(progress, f"🔁 سشن بررسی‌شده: {index} از {len(files)}" + recent_error_preview(errors))
    await safe_edit(progress, "❌ هیچ سشن قابل استفاده‌ای چت را سین نکرد." + recent_error_preview(errors))
    if errors:
        await send_text_report(message, "خطاهای سین", errors, "seen_errors.txt")


async def sine_forward_handle(message, user_id):
    try:
        chat_id, chat_type = get_forward_chat_target(message)
    except ValueError as exc:
        await message.reply(f"❌ {exc}")
        return
    user_data.pop(user_id, None)
    await run_exclusive(message, "سین چت", mark_seen_all_sessions, message, chat_id, chat_type)


async def send_single_report(message, chat_id, chat_type, reason):
    files = get_session_files()
    progress = await message.reply("⨻ در حال ارسال یک گزارش معتبر...")
    errors = []
    for index, path in enumerate(files, 1):
        client = None
        try:
            client = Client(Dispatcher(), session_file=str(path))
            await asyncio.wait_for(client.get_me(), timeout=35)
            resolved_type = chat_type
            if chat_type in (ChatType.GROUP, ChatType.CHANNEL, ChatType.SUPER_GROUP):
                resolved_type = await resolve_group_chat_type(client, chat_id, chat_type)
            else:
                resolved_type = await resolve_private_chat_type(client, chat_id)
            await asyncio.wait_for(client.report_chat(chat_id=chat_id, chat_type=resolved_type, reason=reason), timeout=45)
            await safe_edit(
                progress,
                "✅ گزارش ارسال شد.\n\n"
                f"نوع: {chat_type_label(resolved_type)}\nآیدی: {chat_id}\nسشن: {path.name}\nدلیل: {reason}",
            )
            return
        except asyncio.CancelledError:
            raise
        except Exception as exc:
            error = f"{path.name}: {short_error(exc)}"
            errors.append(error)
            write_debug_log("report", exc, error)
        finally:
            await safe_stop(client)
        if should_update(index, len(files)):
            await safe_edit(progress, f"⨻ سشن بررسی‌شده: {index} از {len(files)}" + recent_error_preview(errors))
    await safe_edit(progress, "❌ هیچ سشن سالمی گزارش را ارسال نکرد." + recent_error_preview(errors))
    if errors:
        await send_text_report(message, "خطاهای گزارش", errors, "report_errors.txt")


async def smart_report_start(message, user_id):
    user_data[user_id] = {"action": "smart_report_chat"}
    await message.reply(
        "📤 گزارش هوشمند\n\nآیدی چت و نوع آن را در دو خط بفرستید:\n"
        "خط اول: آیدی عددی\nخط دوم: 1 خصوصی، 2 کانال، 3 گروه\n\n"
        "گزارش فقط یک‌بار، با دلیل واقعی و بدون متن تصادفی ثبت می‌شود."
    )


async def smart_report_chat_handle(message, user_id, text):
    parts = [part.strip() for part in convert_to_english_numbers(text).splitlines() if part.strip()]
    if len(parts) != 2 or not parts[0].lstrip("-").isdigit():
        await message.reply("⚠️ فرمت صحیح دو خط است: آیدی چت و نوع 1/2/3.")
        return
    chat_type = parse_chat_type_code(parts[1])
    if chat_type is None:
        await message.reply("⚠️ نوع چت باید 1، 2 یا 3 باشد.")
        return
    user_data[user_id] = {"action": "smart_report_reason", "chat_id": int(parts[0]), "chat_type": chat_type}
    await message.reply("📝 دلیل واقعی گزارش را بنویسید؛ حداقل ۵ نویسه.")


async def smart_report_message_handle(message, user_id, text):
    # Kept for backward-compatible saved states; no bait message is sent.
    await smart_report_reason_handle(message, user_id, text)


async def smart_report_reason_handle(message, user_id, text):
    state = user_data.get(user_id, {})
    reason = str(text or "").strip()
    if len(reason) < 5:
        await message.reply("⚠️ دلیل گزارش باید حداقل ۵ نویسه باشد.")
        return
    chat_id = state.get("chat_id") if isinstance(state, dict) else None
    chat_type = state.get("chat_type") if isinstance(state, dict) else None
    if not chat_id or chat_type is None:
        user_data.pop(user_id, None)
        await message.reply("❌ اطلاعات عملیات ناقص است؛ دوباره شروع کنید.")
        return
    user_data.pop(user_id, None)
    await run_exclusive(message, "ارسال گزارش معتبر", send_single_report, message, int(chat_id), chat_type, reason)


async def smart_report_forward_handle(message, user_id):
    user_data.pop(user_id, None)
    await message.reply("⚠️ در نسخه ایمن، گزارش بر اساس پاسخ فورواردشده یا متن تصادفی اجرا نمی‌شود.")

# ---------- End Session Messaging Features ----------



async def handle_document_upload(message):
    document = message.document
    name = sanitize_upload_name(document.name or "upload")
    lower_name = name.lower()
    user_id = message.author.id
    user_data.pop(user_id, None)
    declared_size = get_document_size(document)
    if declared_size is not None and declared_size > MAX_UPLOAD_SIZE:
        await message.reply("❌ حجم فایل ارسالی بیشتر از حد مجاز است.")
        return

    if lower_name.endswith(".bale"):
        content = await bot.download(document.id)
        if len(content) > MAX_SESSION_FILE_SIZE:
            await message.reply("❌ حجم فایل سشن بیشتر از حد مجاز است.")
            return
        temp_path = CHECK_DIR / f"temp_{int(time.time() * 1000)}_{name}"
        temp_path.write_bytes(content)
        ok, me, error = await validate_session_file(temp_path)
        try:
            if ok:
                final_path = copy_session_unique(temp_path, name)
                renamed_note = "" if final_path.name == name else f"\nℹ️ برای جلوگیری از بازنویسی، با نام {final_path.name} ذخیره شد."
                await message.reply(
                    "✅ فایل سشن سالم بود و ذخیره شد.\n"
                    f"📁 نام فایل: {final_path.name}\n"
                    f"🆔 آیدی حساب: {getattr(me, 'id', 'نامشخص')}"
                    + renamed_note
                )
            else:
                await message.reply(f"❌ فایل سشن خراب یا نامعتبر است.\n{error}")
        finally:
            unlink_quietly(temp_path)
        return

    if lower_name.endswith(".zip"):
        start = await message.reply("📥 در حال دانلود و بررسی فایل ZIP...")
        content = await bot.download(document.id)
        zip_path = CHECK_DIR / f"sessions_{int(time.time() * 1000)}.zip"
        zip_path.write_bytes(content)
        ok_count = 0
        bad_count = 0
        renamed_count = 0
        skipped_large = 0
        try:
            with zipfile.ZipFile(zip_path, "r") as archive:
                members = [
                    item for item in archive.infolist()
                    if not item.is_dir() and item.filename.lower().endswith(".bale")
                ]
                if not members:
                    await safe_edit(start, "❌ داخل فایل ZIP هیچ سشن .bale پیدا نشد.")
                    return
                if len(members) > MAX_ZIP_SESSION_COUNT:
                    await safe_edit(
                        start,
                        f"❌ تعداد سشن‌های ZIP بیشتر از حد مجاز ({MAX_ZIP_SESSION_COUNT}) است."
                    )
                    return
                total_uncompressed = sum(max(0, int(item.file_size)) for item in members)
                if total_uncompressed > MAX_ZIP_UNCOMPRESSED_SIZE:
                    await safe_edit(start, "❌ حجم استخراج‌شده ZIP بیش از حد مجاز است.")
                    return

                for index, member in enumerate(members, 1):
                    file_name = os.path.basename(member.filename)
                    if not file_name:
                        bad_count += 1
                        continue
                    if member.file_size > MAX_SESSION_FILE_SIZE:
                        skipped_large += 1
                        continue
                    temp_path = CHECK_DIR / f"temp_{index}_{int(time.time() * 1000)}_{file_name}"
                    try:
                        with archive.open(member, "r") as source:
                            payload = source.read(MAX_SESSION_FILE_SIZE + 1)
                        if len(payload) > MAX_SESSION_FILE_SIZE:
                            skipped_large += 1
                            continue
                        temp_path.write_bytes(payload)
                        ok, _, _ = await validate_session_file(temp_path)
                        if ok:
                            final_path = copy_session_unique(temp_path, file_name)
                            if final_path.name != file_name:
                                renamed_count += 1
                            ok_count += 1
                        else:
                            bad_count += 1
                    except Exception:
                        bad_count += 1
                    finally:
                        unlink_quietly(temp_path)
                    if should_update(index, len(members)):
                        await safe_edit(
                            start,
                            f"📦 بررسی ZIP: {index} از {len(members)}\n"
                            f"✅ ذخیره‌شده: {ok_count}\n"
                            f"❌ خراب: {bad_count}\n"
                            f"⏭ بزرگ و ردشده: {skipped_large}"
                        )
                await safe_edit(
                    start,
                    "✅ بررسی ZIP تمام شد.\n\n"
                    f"📊 کل سشن‌ها: {len(members)}\n"
                    f"✅ سالم و ذخیره‌شده: {ok_count}\n"
                    f"❌ خراب: {bad_count}\n"
                    f"⏭ بزرگ و ردشده: {skipped_large}\n"
                    f"📝 تغییر نام برای جلوگیری از بازنویسی: {renamed_count}"
                )
        except zipfile.BadZipFile:
            await safe_edit(start, "❌ فایل ZIP خراب است یا فرمت معتبری ندارد.")
        finally:
            unlink_quietly(zip_path)
        return

    await message.reply("⚠️ فقط فایل‌های .bale و .zip پشتیبانی می‌شوند.")


async def route_message(message):
    user_id = message.author.id
    if user_id not in admins:
        return

    ensure_join_guard_task()
    text = (message.text or "").strip()
    active_operation = ACTIVE_OPERATIONS.get(user_id)
    if active_operation and text in {"/cancel", "❌ لغو خروج", "⏹ توقف عملیات"}:
        user_data.pop(user_id, None)
        await cancel_active_operation(message, user_id)
        return
    if active_operation:
        await message.reply(
            f"⏳ عملیات «{active_operation_name(active_operation)}» در حال اجراست.\n"
            "ربات قفل نیست؛ برای توقف /cancel را ارسال کنید."
        )
        return

    # Check for forwarded messages for reaction, seen, and smart report.
    if is_forwarded_message(message):
        action = state_action(user_id)
        if action == "reaction_forward":
            await reaction_forward_handle(message, user_id)
            return
        elif action == "sine_forward":
            await sine_forward_handle(message, user_id)
            return
        elif action == "smart_report_waiting":
            await smart_report_forward_handle(message, user_id)
            return
        # else ignore forward

    if message.document:
        await handle_document_upload(message)
        return

    if text == "/cancel":
        state = user_data.pop(user_id, None)
        # Set cancellation flag for ongoing operations
        if isinstance(state, dict):
            # preserve state but set cancel flag
            state["cancel"] = True
            user_data[user_id] = state
        else:
            user_data[user_id] = {"cancel": True}
        if isinstance(state, dict) and state.get("phone"):
            unlink_quietly(SESSIONS_DIR / f"{state['phone']}.bale")
        await message.reply("❌ عملیات لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))
        return

    confirmation_controls = {
        "✅ تایید خروج همه", "❌ لغو خروج",
        "✅ تایید انتقال مالکیت", "❌ لغو انتقال مالکیت",
        "✅ تایید ارسال پاکت‌ها", "❌ لغو ارسال پاکت‌ها",
        "✅ تایید پاک‌کردن مجازها", "❌ لغو پاک‌کردن مجازها",
        "✅ تایید ارسال پیوی", "✅ تایید ارسال گروه‌ها", "✅ تایید ارسال پیام",
        "✅ تایید تغییر نام همه", "❌ لغو تغییر نام همه",
        "✅ تایید پاک کردن بیو همه", "❌ لغو پاک کردن بیو همه",
    "➕ افزودن پیوی مجاز", "➖ حذف پیوی مجاز", "📋 پیوی‌های مجاز",
        "❌ لغو ارسال همگانی", "✅ تایید گزارش", "❌ لغو گزارش"
    }
    if text in CONTROL_TEXTS and text not in confirmation_controls:
        user_data.pop(user_id, None)

    if text == "/start":
        await message.reply(
            "✨ *به پنل مدیریت ربات خوش آمدید*\n\n"
            "از دکمه‌های زیر استفاده کنید. هر دکمه‌ای که بزنید، عملیات قبلی لغو می‌شود تا ورودی‌ها با هم تداخل نکنند.",
            ReplyKeyboard(*MAIN_KEYBOARD)
        )

    elif text == "🔙 بازگشت":
        await message.reply("🔙 بازگشت به منوی اصلی", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "📊 اطلاعات کامل":
        files = get_session_files()
        if not files:
            await message.reply("📭 سشنی وجود ندارد.")
            return
        loading = await message.reply("🔄 در حال دریافت اطلاعات...")
        healthy = 0
        unhealthy = 0
        money = 0
        for index, path in enumerate(files, 1):
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                await asyncio.wait_for(client.get_me(), timeout=35)
                healthy += 1
                try:
                    wallet = await asyncio.wait_for(client.get_wallet(), timeout=45)
                    money += int(wallet.wallet.balance) // 10
                except Exception:
                    pass
            except Exception:
                unhealthy += 1
            finally:
                await safe_stop(client)
            if should_update(index, len(files)):
                await safe_edit(loading, f"🔄 در حال دریافت اطلاعات... ({index} از {len(files)})")
        await safe_edit(loading, 
            "📊 *گزارش کامل وضعیت اکانت‌ها*\n\n"
            f"• کل اکانت‌ها: {len(files)}\n"
            f"• اکانت‌های سالم: {healthy}\n"
            f"• اکانت‌های خراب: {unhealthy}\n"
            f"• مجموع موجودی: {money:,} تومان"
        )

    elif text == "📥 جوین دسته‌جمعی":
        await message.reply(
            "📥 فرمت جوین دسته‌جمعی:\n\n"
            "عضو شو\n"
            "5\n"
            "https://ble.ai/join/ABCDEFG"
        )

    elif text.startswith("عضو شو"):
        parts = [part.strip() for part in text.splitlines() if part.strip()]
        if len(parts) != 3 or not parts[1].isdigit() or int(parts[1]) <= 0:
            await message.reply("⚠️ فرمت صحیح:\nعضو شو\n5\nلینک گروه")
            return
        number = int(parts[1])
        link = parts[2]
        add_group(link)
        files = get_session_files()
        if not files:
            await message.reply("📭 سشنی وجود ندارد.")
            return
        start = await message.reply("🔄 در حال پیدا کردن سشن‌های سالم...")
        accounts = await get_healthy_session_paths(number, start)
        if not accounts:
            await safe_edit(start, "❌ هیچ سشن سالمی پیدا نشد.")
            return
        await safe_edit(start, f"📥 شروع عضویت با {len(accounts)} سشن سالم...")
        success = 0
        failed = 0
        delay = get_delay()
        for index, path in enumerate(accounts, 1):
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                await asyncio.wait_for(client.join_chat(link), timeout=45)
                try:
                    preview = await asyncio.wait_for(client.get_group_preview(link), timeout=20)
                    add_allowed_chat_id(as_int(getattr(preview, "id", 0)))
                except Exception:
                    pass
                success += 1
            except Exception:
                failed += 1
            finally:
                await safe_stop(client)
            if delay:
                await asyncio.sleep(delay)
            if should_update(index, len(accounts)):
                await safe_edit(start, f"📥 عضویت: {index} از {len(accounts)}\n✅ {success}\n❌ {failed}")
        await safe_edit(start, 
            "✅ عملیات جوین تمام شد.\n\n"
            f"درخواستی: {number}\n"
            f"سشن سالم استفاده‌شده: {len(accounts)}\n"
            f"موفق: {success}\n"
            f"ناموفق: {failed}"
        )

    elif text == "📤 لیو دسته‌جمعی":
        await message.reply(
            "📤 فرمت لیو دسته‌جمعی:\n\n"
            "لفت بده پیشرفته\n"
            "10\n"
            "https://ble.ai/join/ABCDEFG"
        )

    elif text.startswith("لفت بده پیشرفته"):
        parts = [part.strip() for part in text.splitlines() if part.strip()]
        if len(parts) != 3 or not parts[1].isdigit() or int(parts[1]) <= 0:
            await message.reply("⚠️ فرمت صحیح:\nلفت بده پیشرفته\n10\nلینک گروه")
            return
        number = int(parts[1])
        link = parts[2]
        files = get_session_files()
        start = await message.reply("🔄 در حال شناسایی اعضای گروه...")
        accounts = []
        for index, path in enumerate(files, 1):
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                await asyncio.wait_for(client.get_me(), timeout=35)
                preview = await asyncio.wait_for(client.get_group_preview(link), timeout=30)
                if getattr(preview, "is_joined", False):
                    accounts.append((path, int(preview.id)))
            except Exception:
                pass
            finally:
                await safe_stop(client)
            if should_update(index, len(files)):
                await safe_edit(start, 
                    f"🔄 بررسی عضویت: {index} از {len(files)}\n"
                    f"عضو پیدا شده: {len(accounts)} از {number}"
                )
            if len(accounts) >= number:
                break
        if not accounts:
            await safe_edit(start, "ℹ️ هیچ‌کدام از سشن‌های سالم عضو این گروه نبودند.")
            return
        success = 0
        failed = 0
        delay = get_delay()
        for index, (path, chat_id) in enumerate(accounts, 1):
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                await asyncio.wait_for(client.leave_group(chat_id), timeout=30)
                success += 1
            except Exception:
                failed += 1
            finally:
                await safe_stop(client)
            if delay:
                await asyncio.sleep(delay)
            if should_update(index, len(accounts)):
                await safe_edit(start, f"🚶 خروج: {index} از {len(accounts)}\n✅ {success}\n❌ {failed}")
        await safe_edit(start, 
            "✅ عملیات لیو تمام شد.\n\n"
            f"درخواستی: {number}\n"
            f"عضو پیدا شده: {len(accounts)}\n"
            f"موفق: {success}\n"
            f"ناموفق: {failed}"
        )

    elif text == "🔍 بررسی سشن‌ها":
        await run_exclusive(message, "بررسی و بررسی و قرنطینه سشن‌ها", check_and_clean_sessions, message)

    elif text == "✨ ساخت سشن":
        user_data[user_id] = {"action": "create_session_phone"}
        await message.reply(
            "📱 شماره تلفن را ارسال کنید.\n"
            "نمونه: 989123456789 یا 09123456789\n"
            "لغو: /cancel"
        )

    elif text == "🚪 خروج همه از کانال‌ها و گروه‌ها":
        keyboard = [["✅ تایید خروج همه"], ["❌ لغو خروج", "🔙 بازگشت"]]
        await message.reply(
            "⚠️ این عملیات تمام سشن‌های سالم را از همه گروه‌ها و کانال‌هایی که عضو هستند خارج می‌کند.\n"
            "برای شروع، تأیید کنید. بعد از شروع، با همین دکمه لغو یا /cancel می‌توانید عملیات را متوقف کنید.",
            ReplyKeyboard(*keyboard)
        )

    elif text == "✅ تایید خروج همه":
        user_data.pop(user_id, None)
        await run_exclusive(message, "خروج همه از کانال‌ها و گروه‌ها", leave_all_groups_for_all_sessions, message)

    elif text == "❌ لغو خروج":
        user_data.pop(user_id, None)
        await message.reply("❌ عملیات خروج همگانی لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "✅ تایید انتقال مالکیت":
        await run_exclusive(message, "انتقال مالکیت", execute_ownership_transfer, message, user_id)

    elif text == "❌ لغو انتقال مالکیت":
        user_data.pop(user_id, None)
        await message.reply("❌ انتقال مالکیت لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "✅ تایید ارسال پاکت‌ها":
        await run_exclusive(message, "ارسال پاکت‌ها", execute_balance_collection, message, user_id)

    elif text == "❌ لغو ارسال پاکت‌ها":
        user_data.pop(user_id, None)
        await message.reply("❌ ارسال پاکت‌ها لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "⚙️ تنظیمات":
        guard_status = "روشن ✅" if is_join_guard_enabled() else "خاموش ⛔"
        keyboard = [
            ["⏱ تغییر Delay"],
            ["🛡 محافظ عضویت"],
            ["🔎 بررسی عضویت‌ها الان", "📋 لیست مجازها"],
            ["🗑 پاک کردن لیست مجازها"],
            ["➕ افزودن پیوی مجاز", "➖ حذف پیوی مجاز"],
            ["📋 پیوی‌های مجاز"],
            ["🧹 پاکسازی گروه‌های ذخیره‌شده"],
            ["🚪 خروج همه از کانال‌ها و گروه‌ها"],
            ["🔙 بازگشت"]
        ]
        await message.reply(
            f"⚙️ تنظیمات\n\nDelay فعلی: {get_delay()} ثانیه\n"
            f"محافظ عضویت: {guard_status}\n"
            f"فاصله بررسی خودکار: {get_join_guard_interval() // 60} دقیقه",
            ReplyKeyboard(*keyboard)
        )

    elif text == "🛡 محافظ عضویت":
        enabled = is_join_guard_enabled()
        keyboard = [
            ["⛔ غیرفعال‌سازی محافظ" if enabled else "✅ فعال‌سازی محافظ"],
            ["🔎 بررسی عضویت‌ها الان", "📋 لیست مجازها"],
            ["🔙 بازگشت"]
        ]
        await message.reply(
            "🛡 محافظ عضویت غیرمجاز\n\n"
            f"وضعیت: {'روشن ✅' if enabled else 'خاموش ⛔'}\n"
            f"لینک‌های مجاز: {len(get_group())}\n"
            f"آیدی‌های مجاز: {len(get_allowed_chat_ids())}\n"
            f"دوره بررسی: {get_join_guard_interval() // 60} دقیقه\n\n"
            "هر لینکی که با دستور «عضو شو» بدهید، خودکار در لیست مجاز ثبت می‌شود. "
            "محافظ فقط گروه‌ها و کانال‌های خارج از این لیست را ترک می‌کند. "
            "گفتگوهایی که سشن مالک آن‌هاست برای جلوگیری از از دست رفتن مالکیت ترک نمی‌شوند.",
            ReplyKeyboard(*keyboard)
        )

    elif text == "✅ فعال‌سازی محافظ":
        if not get_group() and not get_allowed_chat_ids():
            await message.reply(
                "⚠️ لیست مجاز خالی است. ابتدا با دستور «عضو شو» حداقل یک لینک مجاز ثبت کنید؛ "
                "سپس محافظ را روشن کنید."
            )
            return
        set_join_guard_enabled(True)
        ensure_join_guard_task()
        await message.reply(
            "✅ محافظ عضویت فعال شد.\n"
            f"هر {get_join_guard_interval() // 60} دقیقه عضویت‌ها بررسی می‌شوند.\n"
            "برای بررسی فوری، دکمه «🔎 بررسی عضویت‌ها الان» را بزنید."
        )

    elif text == "⛔ غیرفعال‌سازی محافظ":
        set_join_guard_enabled(False)
        await stop_join_guard_task()
        await message.reply("⛔ محافظ عضویت غیرفعال شد.")

    elif text == "🔎 بررسی عضویت‌ها الان":
        await run_exclusive(message, "بررسی عضویت‌های غیرمجاز", run_membership_guard_once, message)

    elif text == "📋 لیست مجازها":
        links = get_group()
        ids = sorted(get_allowed_chat_ids())
        lines = ["📋 لیست مجاز محافظ عضویت", ""]
        lines.append("🔗 لینک‌ها:")
        if links:
            lines.extend(f"{index}. {link}" for index, link in enumerate(links, 1))
        else:
            lines.append("— خالی —")
        lines.append("")
        lines.append("🆔 آیدی‌ها:")
        if ids:
            lines.extend(f"{index}. {chat_id}" for index, chat_id in enumerate(ids, 1))
        else:
            lines.append("— هنوز استخراج نشده —")
        await send_text_chunks(message, "\n".join(lines))

    elif text == "🗑 پاک کردن لیست مجازها":
        keyboard = [["✅ تایید پاک‌کردن مجازها"], ["❌ لغو پاک‌کردن مجازها", "🔙 بازگشت"]]
        await message.reply(
            "⚠️ با پاک‌کردن لیست مجاز، محافظ نیز خاموش می‌شود. تأیید می‌کنید؟",
            ReplyKeyboard(*keyboard)
        )

    elif text == "✅ تایید پاک‌کردن مجازها":
        clear_join_allowlist()
        await stop_join_guard_task()
        await message.reply("✅ لینک‌ها و آیدی‌های مجاز پاک شدند و محافظ خاموش شد.")

    elif text == "❌ لغو پاک‌کردن مجازها":
        await message.reply("❌ پاک‌کردن لیست مجاز لغو شد.")

    elif text == "➕ افزودن پیوی مجاز":
        user_data[user_id] = {"action": "add_private_allowlist"}
        await message.reply("🆔 آیدی عددی پیوی مجاز را ارسال کنید.")

    elif text == "➖ حذف پیوی مجاز":
        user_data[user_id] = {"action": "remove_private_allowlist"}
        await message.reply("🆔 آیدی عددی پیوی را برای حذف ارسال کنید.")

    elif text == "📋 پیوی‌های مجاز":
        ids = sorted(get_allowed_private_ids())
        if not ids:
            await message.reply("📭 فهرست پیوی‌های مجاز خالی است.")
        else:
            await send_text_chunks(message, "📋 پیوی‌های مجاز:\n\n" + "\n".join(f"{i}. {chat_id}" for i, chat_id in enumerate(ids, 1)))

    elif text == "⏱ تغییر Delay":
        user_data[user_id] = {"action": "change_delay"}
        await message.reply("⏱ مقدار جدید Delay را به ثانیه بفرستید. لغو: /cancel")

    elif text == "🧹 پاکسازی گروه‌های ذخیره‌شده":
        groups = get_group()
        if not groups:
            await message.reply("📭 لیست گروه‌های ذخیره‌شده خالی است.")
            return
        files = get_session_files()
        start = await message.reply("🧹 پاکسازی گروه‌های ذخیره‌شده شروع شد...")
        success = 0
        failed = 0
        delay = get_delay()
        for group_index, link in enumerate(groups, 1):
            group_had_success = False
            for path in files:
                client = None
                try:
                    client = Client(Dispatcher(), session_file=str(path))
                    await asyncio.wait_for(client.get_me(), timeout=35)
                    preview = await asyncio.wait_for(client.get_group_preview(link), timeout=30)
                    if getattr(preview, "is_joined", False):
                        await client.leave_group(int(preview.id))
                        success += 1
                        group_had_success = True
                except Exception:
                    failed += 1
                finally:
                    await safe_stop(client)
                if delay:
                    await asyncio.sleep(delay)
            remove_group(link)
            await safe_edit(start, 
                f"🧹 گروه ذخیره‌شده: {group_index} از {len(groups)}\n"
                f"✅ خروج موفق: {success}\n"
                f"⚠️ ناموفق: {failed}"
            )
        await safe_edit(start, 
            "✅ پاکسازی گروه‌های ذخیره‌شده تمام شد.\n\n"
            f"✅ خروج موفق: {success}\n"
            f"⚠️ ناموفق: {failed}"
        )

    elif text == "💻 مدیریت سشن":
        keyboard = [
            ["📱 شماره‌ها", "📞 شماره از نام فایل"],
            ["ℹ️ اطلاعات سشن", "⪢ ورود به اکانت"],
            ["✏️ تغییر نام همه", "🧹 پاک کردن بیو همه"],
            ["📚 همه کانال‌ها و گروه‌ها", "👑 مالکیت‌های سشن‌ها"],
            ["👑 انتقال مالکیت", "💰 تجمیع موجودی"],
            ["⨠ به روزرسانی دیتابیس", "🔍 سرچ سشن"],
            ["🔙 بازگشت"]
        ]
        await message.reply("💻 مدیریت سشن", ReplyKeyboard(*keyboard))

    elif text == "📱 شماره‌ها":
        await list_session_numbers(message)

    elif text == "📞 شماره از نام فایل":
        user_data[user_id] = {"action": "session_phone_lookup"}
        await message.reply("📁 نام فایل سشن را بفرستید؛ نمونه: 989123456789.bale")

    elif text == "✏️ تغییر نام همه":
        user_data[user_id] = {"action": "bulk_rename_input"}
        await message.reply("✏️ نام جدید را بفرستید. پس از آن تأیید نهایی گرفته می‌شود.")

    elif text == "🧹 پاک کردن بیو همه":
        user_data[user_id] = {"action": "confirm_clear_all_bios"}
        await message.reply(
            "⚠️ بیوی تمام حساب‌های سالم خالی می‌شود. ادامه می‌دهید؟",
            ReplyKeyboard(*[["✅ تایید پاک کردن بیو همه"], ["❌ لغو پاک کردن بیو همه", "🔙 بازگشت"]]),
        )

    elif text == "ℹ️ اطلاعات سشن":
        user_data[user_id] = {"action": "session_information"}
        await message.reply("📁 نام فایل سشن را بفرستید؛ نمونه: 989123215487.bale")

    elif text == "📚 همه کانال‌ها و گروه‌ها":
        await run_exclusive(message, "بررسی همه کانال‌ها و گروه‌ها", scan_group_reports, message, owners_only=False)

    elif text == "👑 مالکیت‌های سشن‌ها":
        await run_exclusive(message, "بررسی مالکیت‌ها", scan_group_reports, message, owners_only=True)

    elif text == "👑 انتقال مالکیت":
        user_data[user_id] = {"action": "transfer_ownership_input"}
        await message.reply(
            "👑 اطلاعات انتقال مالکیت را در سه خط بفرستید:\n"
            "مالک کن\n"
            "آیدی کانال یا گپ\n"
            "آیدی مالک جدید\n\n"
            "نمونه:\nمالک کن\n123456789\n987654321"
        )

    elif text.startswith("مالک کن"):
        parts = [part.strip() for part in convert_to_english_numbers(text).splitlines() if part.strip()]
        if len(parts) != 3 or parts[0] != "مالک کن" or not parts[1].lstrip("-").isdigit() or not parts[2].isdigit():
            await message.reply("⚠️ فرمت صحیح:\nمالک کن\nآیدی کانال یا گپ\nآیدی مالک جدید")
            return
        await run_exclusive(message, "یافتن مالک کانال یا گپ", prepare_ownership_transfer, message, user_id, int(parts[1]), int(parts[2]))

    elif text == "💰 تجمیع موجودی":
        user_data[user_id] = {"action": "collect_balance_target"}
        await message.reply(
            "💰 آیدی عددی حساب مقصد را بفرستید.\n"
            "بعد از بررسی موجودی‌ها، پیش از ارسال پاکت‌ها تأیید نهایی گرفته می‌شود."
        )

    elif text == "⨠ به روزرسانی دیتابیس":
        files = get_session_files()
        start = await message.reply("🔄 در حال به‌روزرسانی دیتابیس...")
        data = {}
        for index, path in enumerate(files, 1):
            client = None
            try:
                client = Client(Dispatcher(), session_file=str(path))
                me = await asyncio.wait_for(client.get_me(), timeout=35)
                phone = clean_phone("", path.name)
                try:
                    full = await asyncio.wait_for(client.get_full_me(), timeout=45)
                    contact = getattr(full, "contact_info", None)
                    phone = clean_phone(getattr(contact, "value", ""), path.name)
                except Exception:
                    pass
                balance = 0
                try:
                    wallet = await asyncio.wait_for(client.get_wallet(), timeout=45)
                    balance = int(wallet.wallet.balance)
                except Exception:
                    pass
                data[str(me.id)] = {
                    "id": int(me.id),
                    "name": str(getattr(me, "name", "")),
                    "phone": phone,
                    "locate": path.name,
                    "money": balance
                }
            except Exception:
                pass
            finally:
                await safe_stop(client)
            if should_update(index, len(files)):
                await safe_edit(start, f"🔄 بررسی: {index} از {len(files)}\n✅ ثبت‌شده: {len(data)}")
        atomic_write_json(SESSIONS_DB_FILE, data)
        await safe_edit(start, f"✅ دیتابیس به‌روزرسانی شد. تعداد حساب ثبت‌شده: {len(data)}")

    elif text == "🔍 سرچ سشن":
        user_data[user_id] = {"action": "search_session"}
        await message.reply("🔎 آیدی، شماره، نام یا نام فایل سشن را ارسال کنید.")

    elif text == "⪢ ورود به اکانت":
        user_data[user_id] = {"action": "login_to_session"}
        await message.reply("📁 نام فایل سشن را ارسال کنید؛ نمونه: 989123456789.bale")

    elif text == "🎩 برترین ها":
        if not SESSIONS_DB_FILE.exists():
            await message.reply("⚠️ ابتدا «به روزرسانی دیتابیس» را اجرا کنید.")
            return
        try:
            with SESSIONS_DB_FILE.open("r", encoding="utf-8") as file:
                data = json.load(file)
        except Exception:
            await message.reply("❌ فایل دیتابیس خراب است؛ دوباره آن را به‌روزرسانی کنید.")
            return
        top = sorted(data.values(), key=lambda item: int(item.get("money", 0)), reverse=True)[:10]
        if not top:
            await message.reply("📭 دیتابیس خالی است.")
            return
        lines = ["🎩 ۱۰ حساب برتر بر اساس موجودی:\n"]
        for index, item in enumerate(top, 1):
            lines.append(
                f"{index}. {item.get('name', '')}\n"
                f"ID: {item.get('id', '')}\n"
                f"Phone: {item.get('phone', '')}\n"
                f"File: {item.get('locate', '')}\n"
                f"Money: {int(item.get('money', 0)):,} ریال\n"
            )
        await message.reply("\n".join(lines))

    elif text == "⨻ گزارش":
        user_data[user_id] = {"action": "report_input"}
        await message.reply(
            "⨻ اطلاعات گزارش را در سه بخش بفرستید:\n\n"
            "خط اول: آیدی عددی چت\n"
            "خط دوم: نوع چت؛ 1 خصوصی، 2 کانال، 3 گروه\n"
            "از خط سوم به بعد: دلیل واقعی گزارش\n\n"
            "نمونه:\n123456789\n1\nارسال پیام‌های توهین‌آمیز"
        )

    # ----- NEW: Advanced send message button -----
    elif text == "📨 ارسال پیام":
        user_data[user_id] = {"action": "advanced_send_input"}
        await message.reply(
            "📨 ارسال پیام پیشرفته\n\n"
            "خط اول: آیدی عددی کاربر\n"
            "خط دوم: نوع مقصد (پیوی/گپ/کانال یا 1/2/3)\n"
            "خط سوم: تعداد سشن‌های استفاده‌شده (عدد)\n"
            "خط چهارم: تعداد بار تکرار (عدد یا 'نامحدود')\n"
            "از خط پنجم تا یکی‌مانده‌به‌آخر: متن پیام\n"
            "خط آخر: تأخیر به ثانیه\n\n"
            "نمونه:\n123456789\nپیوی\n3\n5\nسلام چطوری؟\n2\n\n"
            "برای توقف در حالت نامحدود، /cancel را بفرستید."
        )

    # ----- NEW: Smart report with bait -----
    elif text == "📤 گزارش هوشمند":
        user_data[user_id] = {"action": "smart_report_bait_input"}
        await message.reply(
            "📤 گزارش هوشمند با ارسال پیام\n\n"
            "خط اول: آیدی عددی مقصد\n"
            "خط دوم: نوع مقصد (1 خصوصی، 2 کانال، 3 گروه)\n"
            "خط سوم: متن پیام برای ارسال (بیت)\n"
            "خط چهارم: دلیل گزارش\n\n"
            "نمونه:\n123456789\n1\nاین یک پیام آزمایشی است\nاسپم"
        )

    elif text == "📨 ارسال به همه پیوی":
        user_data[user_id] = {"action": "send_to_private"}
        await message.reply(
            "📨 متن پیام را ارسال کنید.\n"
            "پیام فقط یک‌بار به آیدی‌های موجود در فهرست پیوی‌های مجاز ارسال می‌شود."
        )

    elif text == "📨 ارسال به همه گروه‌ها":
        user_data[user_id] = {"action": "send_to_groups"}
        await message.reply(
            "📨 متن پیام را ارسال کنید.\n"
            "پیام فقط یک‌بار به گروه‌ها و کانال‌های ثبت‌شده در فهرست مجاز ارسال می‌شود."
        )

    elif text == "👁 واکنش":
        await reaction_flow_pick(message, user_id)

    elif text == "🔁 سین":
        user_data[user_id] = {"action": "sine_forward"}
        await message.reply(
            "🔁 یک پیام از چت موردنظر فوروارد کنید.\n"
            "هر سشنی که به آن چت دسترسی داشته باشد، چت را خوانده‌شده علامت می‌زند."
        )

    # Removed old smart report start; now handled above.

    elif text == "✅ تایید ارسال پیام":
        state = user_data.get(user_id, {})
        if state.get("action") != "confirm_advanced_send":
            await message.reply("❌ اطلاعات ارسال پیام پیدا نشد.")
            return
        payload = dict(state)
        user_data.pop(user_id, None)
        await run_exclusive(
            message,
            "ارسال تکراری پیام",
            send_repeated_messages,
            message,
            payload["chat_id"],
            payload["chat_type"],
            payload["session_count"],
            payload["repeat_count"],
            payload["body"],
            payload["delay"],
        )

    elif text == "✅ تایید تغییر نام همه":
        state = user_data.get(user_id, {})
        if not isinstance(state, dict) or state.get("action") != "confirm_bulk_rename":
            await message.reply("❌ نام جدید پیدا نشد.")
            return
        new_name = str(state.get("new_name") or "")
        user_data.pop(user_id, None)
        await run_exclusive(message, "تغییر نام همه حساب‌ها", bulk_change_session_names, message, new_name)

    elif text == "❌ لغو تغییر نام همه":
        user_data.pop(user_id, None)
        await message.reply("❌ تغییر نام همه حساب‌ها لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "✅ تایید پاک کردن بیو همه":
        state = user_data.get(user_id, {})
        if not isinstance(state, dict) or state.get("action") != "confirm_clear_all_bios":
            await message.reply("❌ تأیید عملیات پیدا نشد.")
            return
        user_data.pop(user_id, None)
        await run_exclusive(message, "پاک کردن بیوی همه حساب‌ها", bulk_clear_session_bios, message)

    elif text == "❌ لغو پاک کردن بیو همه":
        user_data.pop(user_id, None)
        await message.reply("❌ پاک‌کردن بیوی همه حساب‌ها لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "✅ تایید ارسال پیوی":
        state = user_data.get(user_id, {})
        if not isinstance(state, dict) or state.get("action") != "confirm_send_private":
            await message.reply("❌ متن آماده ارسال پیدا نشد.")
            return
        body = str(state.get("text") or "")
        user_data.pop(user_id, None)
        await run_exclusive(
            message,
            "ارسال به همه پیوی",
            send_to_all_private,
            message,
            user_id,
            body,
        )

    elif text == "✅ تایید ارسال گروه‌ها":
        state = user_data.get(user_id, {})
        if not isinstance(state, dict) or state.get("action") != "confirm_send_groups":
            await message.reply("❌ متن آماده ارسال پیدا نشد.")
            return
        body = str(state.get("text") or "")
        user_data.pop(user_id, None)
        await run_exclusive(
            message,
            "ارسال به همه گروه‌ها",
            send_to_all_groups,
            message,
            user_id,
            body,
        )

    elif text == "❌ لغو ارسال همگانی":
        user_data.pop(user_id, None)
        await message.reply("❌ ارسال همگانی لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "✅ تایید گزارش":
        state = user_data.get(user_id, {})
        if not isinstance(state, dict) or state.get("action") != "confirm_report":
            await message.reply("❌ اطلاعات گزارش پیدا نشد.")
            return
        chat_id = int(state["chat_id"])
        chat_type = state["chat_type"]
        reason = str(state["reason"])
        user_data.pop(user_id, None)
        await run_exclusive(
            message,
            "ارسال گزارش",
            send_single_report,
            message,
            chat_id,
            chat_type,
            reason,
        )

    elif text == "❌ لغو گزارش":
        user_data.pop(user_id, None)
        await message.reply("❌ گزارش لغو شد.", ReplyKeyboard(*MAIN_KEYBOARD))

    elif text == "📦 دریافت بکاپ":
        start = await message.reply("📦 در حال آماده‌سازی بکاپ...")
        archive_base = CHECK_DIR / f"sessions_backup_{user_id}_{int(time.time())}"
        archive_path = Path(shutil.make_archive(str(archive_base), "zip", root_dir=str(SESSIONS_DIR)))
        try:
            await message.reply_document(
                str(archive_path),
                "📦 بکاپ تمام سشن‌ها\n"
                f"🗓 {datetime.now().strftime('%Y/%m/%d - %H:%M:%S')}"
            )
            try:
                await start.delete()
            except Exception:
                await safe_edit(start, "✅ بکاپ ارسال شد.")
        finally:
            gc.collect()
            try:
                archive_path.unlink()
            except Exception:
                pass

    elif text == "📚 راهنما":
        await message.reply(
            "📚 راهنمای ربات\n\n"
            "• ساخت سشن: شماره را با 98، +98، 09 یا بدون صفر بفرستید.\n"
            "• بررسی سشن‌ها: سشن خراب و تکراری را حذف نمی‌کند؛ به پوشه quarantine منتقل می‌کند.\n"
            "• خروج همه: گفتگوها را صفحه‌به‌صفحه می‌خواند و از گروه‌ها و کانال‌ها خارج می‌شود؛ مالکیت‌ها رد می‌شوند.\n"
            "• محافظ عضویت: لینک‌های دستور عضو شو را مجاز ثبت می‌کند و عضویت‌های خارج از لیست را دوره‌ای ترک می‌کند.\n"
            "• شماره‌ها: نام همه فایل‌های سشن را نمایش می‌دهد.\n"
            "• اطلاعات سشن: اطلاعات حساب، کیف پول، عضویت‌ها و مالکیت‌های یک سشن را نشان می‌دهد.\n"
            "• مالکیت‌های سشن‌ها: کانال‌ها و گپ‌های تحت مالکیت را بر اساس تعداد اعضا مرتب می‌کند.\n"
            "• انتقال مالکیت: با فرمت «مالک کن / آیدی کانال / آیدی مالک جدید» و تأیید نهایی انجام می‌شود.\n"
            "• تجمیع موجودی: از سشن‌های دارای موجودی، پاکت خصوصی برای آیدی مقصد می‌فرستد.\n"
            "• ارسال پیوی/گروه: فقط به مقصدهای ثبت‌شده در فهرست مجاز و پس از تأیید اجرا می‌شود.\n"
            "• واکنش: ایموجی را انتخاب و پیام اصلی را فوروارد کنید؛ اولین سشن دارای دسترسی واکنش را ثبت می‌کند.\n"
            "• سین: پیام را فوروارد کنید تا اولین سشن دارای دسترسی چت را خوانده‌شده کند.\n"
            "• گزارش: یک گزارش با دلیل واقعی و اولین سشن قابل استفاده ارسال می‌کند.\n"
            "• گزارش هوشمند: یک گزارش با دلیل واقعی و بدون متن تصادفی یا پیام تحریک‌کننده ثبت می‌کند.\n"
            "• آپلود: فایل .bale یا ZIP حاوی فایل‌های .bale ارسال کنید.\n"
            "• لغو هر مرحله: /cancel"
        )

    else:
        action = state_action(user_id)
        if action == "create_session_phone":
            await start_session_auth(message, user_id, text)
        elif action == "create_session_code":
            await validate_session_code(message, user_id, text)
        elif action == "create_session_password":
            await validate_session_password(message, user_id, text)
        elif action == "change_delay":
            normalized = convert_to_english_numbers(text)
            if not normalized.isdigit():
                await message.reply("⚠️ Delay باید عدد صحیح و صفر یا بیشتر باشد.")
                return
            value = int(normalized)
            if value > 3600:
                await message.reply("⚠️ حداکثر Delay مجاز ۳۶۰۰ ثانیه است.")
                return
            data = get_data()
            data["delay"] = value
            save_data(data)
            user_data.pop(user_id, None)
            await message.reply(f"✅ Delay روی {value} ثانیه تنظیم شد.")
        elif action == "search_session":
            user_data.pop(user_id, None)
            if not SESSIONS_DB_FILE.exists():
                await message.reply("⚠️ ابتدا دیتابیس را به‌روزرسانی کنید.")
                return
            with SESSIONS_DB_FILE.open("r", encoding="utf-8") as file:
                data = json.load(file)
            query = convert_to_english_numbers(text).strip().lower()
            matches = []
            for item in data.values():
                values = [
                    str(item.get("id", "")), str(item.get("phone", "")),
                    str(item.get("name", "")), str(item.get("locate", ""))
                ]
                if any(query == value.lower() or query in value.lower() for value in values if value):
                    matches.append(item)
            if not matches:
                await message.reply("❌ نتیجه‌ای پیدا نشد.")
            else:
                for item in matches[:20]:
                    await bot.send_message(
                        user_id,
                        f"Name: {item.get('name', '')}\n"
                        f"Phone: {item.get('phone', '')}\n"
                        f"ID: {item.get('id', '')}\n"
                        f"Locate: {item.get('locate', '')}\n"
                        f"Money: {item.get('money', 0)}"
                    )
                await bot.send_message(user_id, f"✅ جستجو تمام شد. نتیجه: {len(matches)}")
        elif action == "login_to_session":
            user_data.pop(user_id, None)
            file_name = os.path.basename(text)
            path = SESSIONS_DIR / file_name
            if not path.exists() or path.suffix.lower() != ".bale":
                await message.reply("❌ فایل سشن پیدا نشد.")
                return
            ok, _, error = await validate_session_file(path)
            if not ok:
                await message.reply(f"❌ سشن خراب است:\n{error}")
                return
            await message.reply("✅ تا ۶۰ ثانیه پیام‌های حاوی Code برای شما ارسال می‌شوند.")
            asyncio.create_task(get_coder(file_name, user_id))
        elif action == "session_information":
            user_data.pop(user_id, None)
            await run_exclusive(message, "دریافت اطلاعات سشن", show_session_information, message, text)
        elif action == "session_phone_lookup":
            user_data.pop(user_id, None)
            await run_exclusive(message, "استخراج شماره سشن", get_phone_from_session_file, message, text)
        elif action == "bulk_rename_input":
            new_name = str(text or "").strip()
            if not new_name:
                await message.reply("⚠️ نام جدید خالی است.")
                return
            if len(new_name) > 64:
                await message.reply("⚠️ نام جدید بیش از حد طولانی است؛ حداکثر ۶۴ نویسه.")
                return
            user_data[user_id] = {"action": "confirm_bulk_rename", "new_name": new_name}
            await message.reply(
                "⚠️ نام تمام حساب‌های سالم تغییر می‌کند.\n\n"
                f"نام جدید: {new_name}",
                ReplyKeyboard(*[["✅ تایید تغییر نام همه"], ["❌ لغو تغییر نام همه", "🔙 بازگشت"]]),
            )
        elif action == "advanced_send_input":
            raw_lines = convert_to_english_numbers(text).splitlines()
            lines = [line.strip() for line in raw_lines if line.strip()]
            if len(lines) < 6:
                await message.reply("⚠️ حداقل ۶ خط لازم است (آیدی، نوع، تعداد سشن، تکرار، متن، تأخیر).")
                return

            # خط اول: آیدی
            if not lines[0].lstrip("-").isdigit():
                await message.reply("⚠️ خط اول باید آیدی عددی باشد.")
                return
            chat_id = int(lines[0])

            # خط دوم: نوع
            type_map = {
                "پیوی": ChatType.PRIVATE, "خصوصی": ChatType.PRIVATE, "1": ChatType.PRIVATE,
                "گپ": ChatType.GROUP, "گروه": ChatType.GROUP, "3": ChatType.GROUP,
                "کانال": ChatType.CHANNEL, "2": ChatType.CHANNEL,
            }
            chat_type = type_map.get(lines[1].lower())
            if chat_type is None:
                await message.reply("⚠️ نوع مقصد نامعتبر است (پیوی/گپ/کانال یا 1/2/3).")
                return

            # خط سوم: تعداد سشن
            if not lines[2].isdigit():
                await message.reply("⚠️ تعداد سشن باید عدد باشد.")
                return
            session_count = int(lines[2])
            if session_count < 1:
                await message.reply("⚠️ تعداد سشن باید حداقل ۱ باشد.")
                return

            # خط چهارم: تعداد تکرار
            repeat_raw = lines[3].strip()
            if repeat_raw.lower() == "نامحدود":
                repeat_count = "نامحدود"
            elif repeat_raw.isdigit():
                repeat_count = int(repeat_raw)
                if repeat_count < 1:
                    await message.reply("⚠️ تعداد تکرار باید حداقل ۱ یا 'نامحدود' باشد.")
                    return
            else:
                await message.reply("⚠️ تعداد تکرار باید عدد یا 'نامحدود' باشد.")
                return

            # خط آخر: تأخیر
            delay_text = lines[-1]
            if not delay_text.isdigit():
                await message.reply("⚠️ خط آخر باید تأخیر عددی برحسب ثانیه باشد.")
                return
            delay_value = int(delay_text)
            if delay_value > 300:
                await message.reply("⚠️ حداکثر تأخیر ۳۰۰ ثانیه است.")
                return

            # متن پیام (از خط پنجم تا یکی‌مانده‌به‌آخر)
            body = "\n".join(lines[4:-1]).strip()
            if not body:
                await message.reply("⚠️ متن پیام خالی است.")
                return

            user_data[user_id] = {
                "action": "confirm_advanced_send",
                "chat_id": chat_id,
                "chat_type": chat_type,
                "session_count": session_count,
                "repeat_count": repeat_count,
                "body": body,
                "delay": delay_value,
            }

            preview = body if len(body) <= 700 else body[:700] + "…"
            repeat_display = repeat_count if repeat_count != "نامحدود" else "نامحدود"
            await message.reply(
                "⚠️ تأیید ارسال پیشرفته\n\n"
                f"آیدی: {chat_id}\nنوع: {chat_type_label(chat_type)}\n"
                f"تعداد سشن: {session_count}\nتعداد تکرار: {repeat_display}\n"
                f"تأخیر: {delay_value} ثانیه\nمتن:\n{preview}",
                ReplyKeyboard(*[["✅ تایید ارسال پیام"], ["❌ لغو ارسال همگانی", "🔙 بازگشت"]]),
            )
        elif action == "transfer_ownership_input":
            normalized = convert_to_english_numbers(text)
            parts = [part.strip() for part in normalized.splitlines() if part.strip()]
            if len(parts) == 3 and parts[0] == "مالک کن":
                parts = parts[1:]
            if len(parts) != 2 or not parts[0].lstrip("-").isdigit() or not parts[1].isdigit():
                await message.reply(
                    "⚠️ دو آیدی عددی را در دو خط بفرستید، یا از فرمت زیر استفاده کنید:\n"
                    "مالک کن\nآیدی کانال یا گپ\nآیدی مالک جدید"
                )
                return
            await run_exclusive(message, "یافتن مالک کانال یا گپ", prepare_ownership_transfer, message, user_id, int(parts[0]), int(parts[1]))
        elif action == "collect_balance_target":
            normalized = convert_to_english_numbers(text).strip()
            if not normalized.isdigit() or int(normalized) <= 0:
                await message.reply("⚠️ آیدی مقصد باید یک عدد مثبت باشد.")
                return
            await run_exclusive(message, "بررسی موجودی سشن‌ها", prepare_balance_collection, message, user_id, int(normalized))
        elif action == "report_input":
            parts = [part.strip() for part in convert_to_english_numbers(text).splitlines() if part.strip()]
            if len(parts) < 3 or not parts[0].lstrip("-").isdigit():
                await message.reply(
                    "⚠️ فرمت صحیح:\nآیدی چت\nنوع 1/2/3\nدلیل واقعی گزارش"
                )
                return
            chat_type = parse_chat_type_code(parts[1])
            if chat_type is None:
                await message.reply("⚠️ نوع چت باید 1، 2 یا 3 باشد.")
                return
            reason = "\n".join(parts[2:]).strip()
            if len(reason) < 5:
                await message.reply("⚠️ دلیل گزارش باید حداقل ۵ نویسه باشد.")
                return
            chat_id = int(parts[0])
            user_data[user_id] = {
                "action": "confirm_report",
                "chat_id": chat_id,
                "chat_type": chat_type,
                "reason": reason,
            }
            await message.reply(
                "⚠️ تأیید گزارش\n\n"
                f"آیدی: {chat_id}\n"
                f"نوع: {chat_type_label(chat_type)}\n"
                f"دلیل: {reason}\n\n"
                "این عملیات فقط یک‌بار با اولین سشن قابل استفاده اجرا می‌شود.",
                ReplyKeyboard(*[["✅ تایید گزارش"], ["❌ لغو گزارش", "🔙 بازگشت"]]),
            )
        elif action == "send_to_private":
            body = str(text or "").strip()
            if not body:
                await message.reply("⚠️ متن پیام خالی است.")
                return
            user_data[user_id] = {"action": "confirm_send_private", "text": body}
            preview = body if len(body) <= 700 else body[:700] + "…"
            await message.reply(
                "⚠️ تأیید ارسال به پیوی‌های مجاز\n\n"
                f"پیش‌نمایش:\n{preview}",
                ReplyKeyboard(*[["✅ تایید ارسال پیوی"], ["❌ لغو ارسال همگانی", "🔙 بازگشت"]]),
            )
        elif action == "send_to_groups":
            body = str(text or "").strip()
            if not body:
                await message.reply("⚠️ متن پیام خالی است.")
                return
            user_data[user_id] = {"action": "confirm_send_groups", "text": body}
            preview = body if len(body) <= 700 else body[:700] + "…"
            await message.reply(
                "⚠️ تأیید ارسال به گروه‌ها و کانال‌های مجاز\n\n"
                f"پیش‌نمایش:\n{preview}",
                ReplyKeyboard(*[["✅ تایید ارسال گروه‌ها"], ["❌ لغو ارسال همگانی", "🔙 بازگشت"]]),
            )
        elif action == "add_private_allowlist":
            normalized = convert_to_english_numbers(text).strip()
            if not normalized.isdigit() or int(normalized) <= 0:
                await message.reply("⚠️ آیدی باید عدد مثبت باشد.")
                return
            add_allowed_private_id(int(normalized))
            user_data.pop(user_id, None)
            await message.reply("✅ آیدی به فهرست پیوی‌های مجاز اضافه شد.")
        elif action == "remove_private_allowlist":
            normalized = convert_to_english_numbers(text).strip()
            if not normalized.isdigit() or int(normalized) <= 0:
                await message.reply("⚠️ آیدی باید عدد مثبت باشد.")
                return
            removed = remove_allowed_private_id(int(normalized))
            user_data.pop(user_id, None)
            await message.reply("✅ آیدی حذف شد." if removed else "ℹ️ این آیدی در فهرست نبود.")
        elif action == "reaction_pick":
            await reaction_pick_handle(message, user_id, text)
        elif action == "smart_report_bait_input":
            lines = [line.strip() for line in convert_to_english_numbers(text).splitlines() if line.strip()]
            if len(lines) != 4:
                await message.reply("⚠️ دقیقاً ۴ خط لازم است: آیدی، نوع، متن بیت، دلیل.")
                return

            if not lines[0].lstrip("-").isdigit():
                await message.reply("⚠️ خط اول باید آیدی عددی باشد.")
                return
            chat_id = int(lines[0])

            chat_type = parse_chat_type_code(lines[1])
            if chat_type is None:
                await message.reply("⚠️ نوع چت باید 1، 2 یا 3 باشد.")
                return

            bait_text = lines[2].strip()
            if not bait_text:
                await message.reply("⚠️ متن بیت خالی است.")
                return

            reason = lines[3].strip()
            if len(reason) < 5:
                await message.reply("⚠️ دلیل گزارش باید حداقل ۵ نویسه باشد.")
                return

            user_data.pop(user_id, None)
            await run_exclusive(
                message,
                "گزارش هوشمند با بیت",
                smart_report_with_bait,
                message,
                chat_id,
                chat_type,
                bait_text,
                reason,
            )
        # keep old smart_report handlers for backward compatibility (if user still in that state)
        elif action == "smart_report_chat":
            await smart_report_chat_handle(message, user_id, text)
        elif action == "smart_report_message":
            await smart_report_message_handle(message, user_id, text)
        elif action == "smart_report_reason":
            await smart_report_reason_handle(message, user_id, text)
        else:
            await message.reply("⚠️ دستور یا ورودی شناخته نشد. /start را بزنید.")


@bot.on_message(private)
async def handler(message: Message):
    try:
        await route_message(message)
    except Exception as exc:
        print(f"handler error: {type(exc).__name__}: {exc}")
        write_debug_log("handler", exc)
        try:
            await message.reply(
                "❌ یک خطای پیش‌بینی‌نشده رخ داد، اما ربات متوقف نشد.\n"
                f"{type(exc).__name__}: {exc}"
            )
        except Exception:
            pass


if __name__ == "__main__":
    bot.run()