"""
bot.py — نقطه ورود پروژه.

ترکیب FastAPI (وب‌هوک تلگرام) + python-telegram-bot v20+ (Application) با MongoDB،
Notion API و OpenAI.

اجرا:
    python bot.py                     # سرور وبهوک (پیش‌فرض)
    POLLING=1 python bot.py           # اجرا با long-polling (برای تست محلی بدون دامنه)
"""

from __future__ import annotations

import asyncio
import logging
import os
import re
import sys
from contextlib import asynccontextmanager
from typing import Any, Optional

import uvicorn
from fastapi import FastAPI, Header, HTTPException, Request
from telegram import BotCommand, Message, Update
from telegram.constants import ChatAction, ChatType, ParseMode
from telegram.error import BadRequest, InvalidToken, NetworkError, TelegramError
from telegram.ext import (
    AIORateLimiter,
    Application,
    ApplicationBuilder,
    CallbackQueryHandler,
    ContextTypes,
    MessageHandler,
    filters,
)

from config.settings import settings
from db import config_store, mongo
from services import setup_wizard
from services.access import allowed_agents, apply_saved_config, is_admin
from services.agents import Agent, load_registry
from services.context import (
    build_agent_context,
    human_today,
    split_for_telegram,
)
from services.automation import AutomationService, _subtask_instruction
from services.orchestrator import build_task_context
from services.tasks import STATUS_TODO, Task, summarize_chain
from services.llm import LLMService
from services.notion import NotionService
from services.sheets_cache import sheet_cache
from services.sources import gather_sources
from services.router import Route, RouteKind, extract_user_question, route_message, strip_mentions

logging.basicConfig(
    level=getattr(logging, settings.log_level.upper(), logging.INFO),
    format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
)
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger("bot")

registry = load_registry()

def build_notion_service() -> NotionService:
    """کلاینت Notion بر اساس تنظیمات فعلی (بعد از هر تغییر تنظیمات نوسازی می‌شود)."""
    return NotionService(
        api_key=settings.notion_api_key,
        api_version=settings.notion_api_version,
        status_property=settings.notion_status_property,
        active_value=settings.notion_status_active_value,
        daily_log_db=settings.notion_daily_log_db,
        daily_log_props={
            "agent": settings.notion_daily_log_agent_prop,
            "mission": settings.notion_daily_log_mission_prop,
            "date": settings.notion_daily_log_date_prop,
            "evidence": settings.notion_daily_log_evidence_prop,
        },
    )


def build_llm_service() -> LLMService:
    provider = (settings.llm_provider or "openai").lower()

    # حالت آفلاین: بدون API، بدون کلید، بدون هزینه
    if provider == "offline":
        from services.offline import build_offline_service

        logger.info("LLM_PROVIDER=offline — پاسخ‌های قاعده‌محور، بدون API")
        return build_offline_service()  # type: ignore[return-value]

    model = settings.openai_model
    if provider != "openai":
        # مدل پیش‌فرض رایگان اگر کاربر مدل OpenAI را نگه داشته باشد
        from services.llm import FREE_MODELS

        default_openai = "gpt-4o"
        if not model or model == default_openai:
            model = FREE_MODELS.get(provider, model)
    return LLMService(
        api_key=settings.active_llm_key,
        model=model,
        temperature=settings.openai_temperature,
        max_tokens=settings.openai_max_tokens,
        timeout=settings.openai_timeout,
        base_url=settings.llm_base_url,
        provider=provider,
    )


notion_service = build_notion_service()
llm_service = build_llm_service()


def refresh_services() -> None:
    """نوسازی کلاینت‌های Notion/LLM پس از تغییر تنظیمات از ویزارد."""
    global notion_service, llm_service
    notion_service = build_notion_service()
    llm_service = build_llm_service()
    logger.info("کلاینت‌های Notion/LLM با تنظیمات جدید نوسازی شدند.")


def build_automation() -> AutomationService:
    """موتور اتوماسیون زنجیره‌ای (وظایف + پولر Notion)."""
    return AutomationService(
        registry=registry,
        notion_service=notion_service,
        llm_service=llm_service,
        mongo_module=mongo,
        get_send_fn=lambda: _send_plain,
    )


async def _send_plain(
    chat_id: int,
    text: str,
    reply_to: Optional[int] = None,
    thread_id: Optional[int] = None,
) -> None:
    """فرستندهٔ ساده برای اعلان‌های اتوماسیون.

    `thread_id` باعث می‌شود پاسخ داخل همان تاپیک گروه برود.
    """
    if telegram_app is None:
        return
    try:
        await telegram_app.bot.send_message(
            chat_id=chat_id,
            text=text,
            parse_mode=ParseMode.HTML,
            reply_to_message_id=reply_to,
            message_thread_id=thread_id,
            disable_web_page_preview=True,
        )
    except TelegramError as exc:
        logger.warning("ارسال اعلان اتوماسیون ناموفق: %s", exc)


automation = build_automation()

# refresh_services باید اتوماسیون را هم نوسازی کند
_original_refresh = refresh_services


def refresh_services() -> None:  # noqa: F811 — نسخهٔ گسترده‌شده
    _original_refresh()
    try:
        automation.registry = registry
        automation.notion = notion_service
        automation.llm = llm_service
        automation.rebuild()
    except Exception:  # noqa: BLE001
        logger.exception("نوسازی اتوماسیون ناموفق بود")


setup_wizard.on_config_applied(refresh_services)


# --------------------------------------------------------------------------- #
#  ۱) ذخیره پیام در MongoDB
# --------------------------------------------------------------------------- #
def _message_to_doc(message: Message) -> dict[str, Any]:
    user = message.from_user
    media_type: Optional[str] = None
    if message.photo:
        media_type = "photo"
    elif message.video:
        media_type = "video"
    elif message.voice:
        media_type = "voice"
    elif message.audio:
        media_type = "audio"
    elif message.document:
        media_type = "document"
    elif message.sticker:
        media_type = "sticker"

    return {
        "message_id": message.message_id,
        "chat_id": message.chat_id,
        "chat_type": message.chat.type,
        "chat_title": message.chat.title or message.chat.username,
        "user_id": user.id if user else None,
        "username": (user.username if user and user.username else (user.full_name if user else "unknown")),
        "sender_name": user.full_name if user else "unknown",
        "is_bot": bool(user and user.is_bot),
        "text": message.text or message.caption or "",
        "entities": [e.to_dict() for e in (message.entities or [])],
        "reply_to_message_id": (
            message.reply_to_message.message_id if message.reply_to_message else None
        ),
        "has_media": media_type is not None,
        "media_type": media_type,
        "date": message.date,
        "edited": False,
    }


async def store_message(message: Message) -> None:
    try:
        await mongo.save_message(
            _message_to_doc(message),
            db_name=settings.mongodb_db,
            collection=settings.chat_history_collection,
        )
    except Exception:  # noqa: BLE001 — ذخیره نباید جریان ربات را قطع کند
        logger.exception("ذخیره پیام در MongoDB ناموفق بود")


# --------------------------------------------------------------------------- #
#  ۲) خواندن داده‌ها برای Context
# --------------------------------------------------------------------------- #
async def _fetch_notion_records(agent: Agent) -> list[dict[str, Any]]:
    db_id = settings.notion_db_id(agent.id)
    if not db_id:
        logger.info("دیتابیس Notion برای %s تنظیم نشده است.", agent.id)
        return []
    return await notion_service.fetch_active_records(db_id, limit=settings.notion_records_limit)


async def _fetch_history(chat_id: int) -> list[dict[str, Any]]:
    try:
        return await mongo.get_last_messages(
            chat_id,
            limit=settings.history_limit,
            db_name=settings.mongodb_db,
            collection=settings.chat_history_collection,
        )
    except Exception:  # noqa: BLE001
        logger.exception("خواندن تاریخچه چت ناموفق بود")
        return []


# --------------------------------------------------------------------------- #
#  ۳) اجرای یک ایجنت
# --------------------------------------------------------------------------- #
async def _keep_typing(bot, chat_id: int, stop: asyncio.Event, thread_id: Optional[int] = None) -> None:
    """ارسال مکرر اکشن «در حال تایپ» تا پایان تولید پاسخ."""
    while not stop.is_set():
        try:
            await bot.send_chat_action(
                chat_id=chat_id, action=ChatAction.TYPING, message_thread_id=thread_id
            )
        except TelegramError:
            pass
        try:
            await asyncio.wait_for(stop.wait(), timeout=4.5)
        except asyncio.TimeoutError:
            continue


async def run_agent(
    agent: Agent,
    message: Message,
    context: ContextTypes.DEFAULT_TYPE,
    question: str,
    status_message: Optional[Message] = None,
) -> str:
    """ساخت Context، فراخوانی LLM، ارسال پاسخ و ثبت daily_log."""
    bot = context.bot
    chat = message.chat
    thread_id = getattr(message, "message_thread_id", None)

    records = await _fetch_notion_records(agent)
    history = await _fetch_history(chat.id)

    # منابع دادهٔ متصل (نسخهٔ ۱.۰.۱) — فقط منابع مجاز همین ایجنت
    try:
        sources = await gather_sources(agent.id, notion_service, sheets=sheet_cache)
    except Exception:  # noqa: BLE001 — منبع خطادار نباید پاسخ را بشکند
        logger.exception("جمع‌آوری منابع برای %s ناموفق بود؛ ادامه بدون منابع", agent.id)
        sources = None

    agent_ctx = build_agent_context(
        agent=agent,
        notion_records=records,
        history_messages=history,
        user_question=question,
        tz_name=settings.display_timezone,
        history_limit=settings.history_limit,
        sources=sources,
    )
    logger.info(
        "%s | notion=%d رکورد | منابع=%d | history=%d پیام | سؤال=%s",
        agent.id,
        len(records),
        len(getattr(sources, "stats", {}) or {}),
        agent_ctx.history_count,
        question[:60],
    )

    stop = asyncio.Event()
    typing_task = asyncio.create_task(_keep_typing(bot, chat.id, stop, thread_id))
    try:
        answer = await llm_service.complete(agent_ctx.system_prompt, agent_ctx.user_prompt)
    finally:
        stop.set()
        typing_task.cancel()
        try:
            await typing_task
        except (asyncio.CancelledError, Exception):  # noqa: BLE001
            pass

    header = f"🤖 <b>{agent.id} — {agent.name}</b>\n<i>مرز اختیار: {agent.authority}</i>\n\n"
    sources_line = ""
    if sources is not None and not getattr(sources, "empty", True):
        stats = ", ".join(
            f"{r.title}={r.count}"
            for r in sources.results
            if getattr(r, "status", "") == "ok"
        ) or "بدون داده"
        sources_line = f"\nمنابع: {stats}"
    footer = (
        f"\n\n<code>Notion: {len(records)} رکورد | تاریخچه: "
        f"{agent_ctx.history_count} پیام{sources_line} | "
        f"{human_today(settings.display_timezone)}</code>"
    )

    chunks = split_for_telegram(answer, limit=settings.max_reply_chars - len(header) - len(footer))
    if not chunks:
        chunks = ["⚠️ پاسخی تولید نشد."]

    # پیام اول: ویرایش پیام وضعیت یا ارسال تازه
    first = header + chunks[0] + (footer if len(chunks) == 1 else "")
    if status_message is not None:
        try:
            await status_message.edit_text(first, parse_mode=ParseMode.HTML)
        except BadRequest as exc:
            logger.warning("ویرایش پیام وضعیت ناموفق (%s)؛ ارسال پیام جدید.", exc)
            status_message = None
    if status_message is None:
        await message.reply_text(first, parse_mode=ParseMode.HTML)

    for chunk in chunks[1:]:
        await message.reply_text(
            f"🤖 <b>{agent.id}</b> (ادامه)\n\n{chunk}", parse_mode=ParseMode.HTML
        )

    # ثبت روزانه در Notion
    if settings.notion_daily_log_db:
        await notion_service.create_daily_log(
            agent_id=agent.id,
            mission_summary=extract_user_question(question or "(بدون متن)"),
            evidence=agent_ctx.evidence_hint,
        )

    return answer


async def _maybe_mention_to_task(message: Message, agent_id: str) -> bool:
    """اگر MENTION_TASK_MODE فعال باشد و شرط‌ها برقرار، منشن را وظیفه کن.

    True = وظیفه ساخته شد (پاسخ فوری نده).
    """
    gate = getattr(automation, "mention_gate", None)
    if automation is None or gate is None or not gate.enabled:
        return False
    if automation.task_store is None or not automation.task_store.available:
        return False

    replied = getattr(message, "reply_to_message", None)
    reply_text = (getattr(replied, "text", None) or getattr(replied, "caption", None) or "") if replied else ""
    reply_author = ""
    if replied is not None and getattr(replied, "from_user", None):
        ru = replied.from_user
        reply_author = ru.username or ru.full_name or ""

    text = message.text or message.caption or ""
    decision = gate.decide(text, [agent_id], is_reply=replied is not None, reply_text=reply_text)
    if not decision.should_create:
        logger.debug("منشن وظیفه نشد (%s): %s", agent_id, decision.reason)
        return False

    try:
        from services.mention_tasks import build_task_from_mention

        user = message.from_user
        task = build_task_from_mention(
            text=text,
            agent_id=agent_id,
            requester=(user.username or user.full_name) if user else "unknown",
            chat_id=message.chat_id,
            message_id=message.message_id,
            reply_text=reply_text,
            reply_author=reply_author,
        )
        created = await automation.task_store.create(task)
        gate.commit()
        logger.info("منشن → وظیفه: %s (%s)", task.title[:60], agent_id)
    except Exception:  # noqa: BLE001
        logger.exception("ساخت وظیفه از منشن ناموفق بود")
        return False

    if created:
        lines = [
            f"🧩 <b>منشن شما وظیفه شد</b> → {agent_id}",
            f"<b>عنوان:</b> {task.title}",
            "<i>وظیفه در Notion ثبت شد؛ ایجنت آن را برمی‌دارد و نتیجه را همین‌جا می‌نویسد.</i>",
        ]
        try:
            await message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML)
        except TelegramError:
            pass
        return True
    return False


async def _ask_orchestrator(message: Message, question: str) -> None:
    """AG09 صدا زده شد → پاسخ می‌دهد و اگر لازم بود زنجیره می‌سازد."""
    status = await message.reply_text("🧠 AG09 در حال تحلیل و برنامه‌ریزی زنجیره…")
    user = message.from_user
    task = Task(
        title=(question or "درخواست به مشاور")[:300],
        assignee="AG09",
        description=question or "",
        status=STATUS_TODO,
        source="telegram",
        chat_id=message.chat_id,
        message_id=message.message_id,
        requester=(user.username or user.full_name) if user else "unknown",
    )
    try:
        if automation.task_store is not None:
            await automation.task_store.create(task)

        extra = build_task_context("AG09", task) + "\n\n" + _subtask_instruction()
        answer = await automation.run_agent("AG09", question or "درخواست مشورتی", extra)
        task.result = answer

        header = "🧠 <b>AG09 — مشاور نهایی / Orchestrator</b>\n\n"
        chunks = split_for_telegram(answer, limit=settings.max_reply_chars - len(header)) or ["—"]
        await status.edit_text(header + chunks[0], parse_mode=ParseMode.HTML)
        for chunk in chunks[1:]:
            await message.reply_text(f"🧠 <b>AG09</b> (ادامه)\n\n{chunk}", parse_mode=ParseMode.HTML)

        chain = await automation.engine.handle_orchestrator_task(task, answer)
        if chain.subtasks:
            await message.reply_text(
                "🧩 <b>زنجیره ساخته شد</b>\n" + summarize_chain(chain.subtasks),
                parse_mode=ParseMode.HTML,
            )
    except Exception:  # noqa: BLE001
        logger.exception("اجرای AG09 ناموفق بود")
        try:
            await status.edit_text("⚠️ خطا در اجرای AG09. جزئیات در لاگ سرور.")
        except TelegramError:
            pass


async def _ask_single_agent(
    agent: Agent, message: Message, context: ContextTypes.DEFAULT_TYPE, question: str
) -> None:
    status = await message.reply_text(
        f"⏳ {agent.id} ({agent.name}) در حال پردازش…", parse_mode=ParseMode.HTML
    )
    try:
        await run_agent(agent, message, context, question, status_message=status)
    except Exception:  # noqa: BLE001
        logger.exception("اجرای ایجنت %s ناموفق بود", agent.id)
        try:
            await status.edit_text(f"⚠️ خطا در اجرای {agent.id}. جزئیات در لاگ سرور.")
        except TelegramError:
            pass


# --------------------------------------------------------------------------- #
#  ۴) هندلر اصلی پیام‌ها
# --------------------------------------------------------------------------- #
async def handle_private_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """پیام‌های پیوی: ویزارد تنظیمات (نه با ایجنت‌ها).

    پیام‌های پیوی در MongoDB ذخیره نمی‌شوند (تنظیمات/کلیدها نباید در تاریخچه گروه بیایند).
    """
    message = update.effective_message
    if message is None:
        return
    if getattr(message, "via_bot", None):
        return

    text = (message.text or "").strip()
    user = message.from_user
    user_id = user.id if user else None
    username = user.username if user else None

    # دستورهای مدیریتی (فقط ادمین‌ها)
    if text.startswith("/"):
        command = text.split()[0].split("@")[0].lower()
        if command in {"/start", "/settings", "/help", "/status"}:
            if command == "/settings":
                await setup_wizard.show_settings(message, context)
            elif command in {"/help", "/status"}:
                await setup_wizard.show_help(message, context)
            else:
                await setup_wizard.start_wizard(message, context)
            return
        if command == "/done":
            await setup_wizard.finish(message, context)
            return
        if command == "/detach":
            await setup_wizard.detach_messages(message, context)
            return
        if command == "/cancel":
            await setup_wizard.cancel(message, context)
            return
        if command == "/id":
            lines = [f"شناسه شما: <code>{user_id}</code>"]
            if username:
                lines.append(f"یوزرنیم: @{username}")
            lines.append("این مقدار را در TELEGRAM_ALLOWED_USER_IDS بگذارید.")
            await message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML)
            return

    # مقدار واردشده در ویزارد
    if await setup_wizard.handle_value(message, context):
        return

    if is_admin(user_id, username):
        await message.reply_text(
            "دستور را نشناختم.\n\n"
            "<b>تنظیمات:</b> <code>/start</code> · <code>/start full</code> · "
            "<code>/settings</code>\n"
            "<b>راهنمای کامل:</b> <code>/help</code>\n"
            "<b>وظیفه (در گروه):</b> <code>/task @A03 عنوان</code>\n"
            "<b>پرسش (در گروه):</b> <code>@ag03 سؤال</code>",
            parse_mode=ParseMode.HTML,
        )
    else:
        await message.reply_text(
            "⛔ این ربات در حالت تنظیمات است.\n"
            f"شناسه شما: <code>{user_id}</code> — آن را به مدیر پروژه بدهید تا دسترسی بگیرید.",
            parse_mode=ParseMode.HTML,
        )


async def handle_callback_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """دکمه‌های شیشه‌ای ویزارد تنظیمات."""
    query = update.callback_query
    if query is None:
        return
    if not (query.data or "").startswith(setup_wizard.WIZARD_ACTION + ":"):
        await query.answer()
        return
    consumed = await setup_wizard.handle_callback(update, context)
    if not consumed:
        await query.answer()


async def _human_mention_hint(message: Message, route: Route) -> None:
    """وقتی کسی یک انسان را منشن می‌کند (@h02).

    سه حالت:
      ۱) خود انسان خودش را منشن کرده → حداقل کاری نکن (شاید عمدی است)
      ۲) منشن‌کننده مجاز است  → پیشنهاد ساخت وظیفه با یک کلیک
      ۳) منشن‌کننده مجاز نیست → فقط اعلام می‌کنیم که پیام به این انسان اشاره دارد
    """
    from services.assignees import get_registry
    from services.access import can_create_tasks

    user = message.from_user
    registry_h = get_registry()
    assignee = registry_h.get(route.agent_id or "")
    if assignee is None:
        return

    in_group = getattr(message.chat, "type", "") != "private"
    allowed = can_create_tasks(
        user.id if user else None,
        user.username if user else None,
        in_group=in_group,
    )
    if not allowed:
        return   # ساکت می‌مانیم تا گروه شلوغ نشود

    thread_id = getattr(message, "message_thread_id", None)
    text = (
        f"👤 این پیام به <b>{assignee.name}</b> (<code>{assignee.code}</code>) اشاره دارد.\n"
        "برای ثبت به‌عنوان <b>وظیفه</b> روی همین پیام ریپلای کن و بنویس:\n"
        f"<code>/task {assignee.code.lower()}</code>"
    )
    try:
        await message.reply_text(
            text,
            parse_mode=ParseMode.HTML,
            disable_web_page_preview=True,
            **({"message_thread_id": thread_id} if thread_id else {}),
        )
    except TelegramError:
        logger.debug("ارسال راهنمای منشن انسانی ناموفق بود")


async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    message = update.effective_message
    if message is None:
        return

    # پیام‌های خصوصی → ویزارد تنظیمات (نه ایجنت)
    if message.chat.type == ChatType.PRIVATE:
        await handle_private_message(update, context)
        return

    # همه پیام‌ها (متن، مدیا، ریپلای) ذخیره می‌شوند
    await store_message(message)

    user = message.from_user
    if user and user.is_bot:
        return  # از حلقه پاسخ بین ربات‌ها جلوگیری می‌کنیم

    text = message.text or message.caption or ""

    # /task → ثبت وظیفه در Notion (قبل از روتینگ ایجنت)
    try:
        handled = await automation.handle_task_message(message)
        if handled:
            return
    except Exception:  # noqa: BLE001 — خطای اتوماسیون نباید پیام را از دست بدهد
        logger.exception("پردازش دستور /task ناموفق بود")

    route: Route = route_message(text, registry)

    if route.kind is RouteKind.IGNORE:
        return  # فقط ذخیره شد

    # منشن انسان (@h02): ربات پاسخ نمی‌دهد — وظیفه‌سازیش با /task است
    if route.kind is RouteKind.HUMAN:
        await _human_mention_hint(message, route)
        return

    question = extract_user_question(text, route.mention_text)

    # کنترل دسترسی اختیاری: اگر ALLOWED_USERS_STRICT=true باشد فقط ادمین‌ها ایجنت صدا می‌زنند
    if not allowed_agents(user.id if user else None, user.username if user else None):
        logger.info("درخواست ایجنت از کاربر غیرمجاز رد شد: %s", user.id if user else None)
        return

    if route.kind is RouteKind.SINGLE:
        agent = registry.get(route.agent_id or "")
        if agent is None:
            return

        # منشن → وظیفه در Notion (اختیاری، MENTION_TASK_MODE)
        if await _maybe_mention_to_task(message, route.agent_id or ""):
            return

        # AG09 = orchestrator → پاسخ می‌دهد و زنجیره می‌سازد
        if agent.id == "AG09" and automation is not None:
            await _ask_orchestrator(message, question)
            return
        await _ask_single_agent(agent, message, context, question)
        return

    if route.kind is RouteKind.ALL:
        targets = registry.enabled_agents()
        if not targets:
            await message.reply_text("هیچ ایجنت فعالی وجود ندارد.")
            return
        status = await message.reply_text(
            "🚀 اجرای همه ایجنت‌های فعال: " + ", ".join(a.id for a in targets)
        )
        shared_question = question or route.extra_args or strip_mentions(text)
        for agent in targets:
            try:
                await run_agent(agent, message, context, shared_question or "(بدون متن)")
            except Exception:  # noqa: BLE001
                logger.exception("اجرای %s در حالت /all ناموفق بود", agent.id)
                await message.reply_text(f"⚠️ {agent.id}: خطا در اجرا (لاگ سرور).")
            await asyncio.sleep(settings.agent_delay_seconds)
        try:
            await status.edit_text(f"✅ اجرای {len(targets)} ایجنت کامل شد.")
        except TelegramError:
            pass
        return

    if route.kind is RouteKind.DISABLED:
        await message.reply_text(
            f"ℹ️ {route.agent_id} ({route.agent_name}) فعلاً غیرفعال است و پاسخ نمی‌دهد.\n"
            "برای فعال‌سازی، در config/agents.yaml مقدار enabled را true کنید."
        )
        return

    if route.kind is RouteKind.DAILY:
        if not is_admin(user.id if user else None, user.username if user else None):
            await message.reply_text("⛔ /daily فقط برای مدیران مجاز است.")
            return
        await handle_daily(message)
        return

    if route.kind is RouteKind.HELP:
        await handle_help(message)
        return

    if route.kind is RouteKind.TASKS:
        await handle_tasks(message)
        return

    if route.kind is RouteKind.WIRING:
        await handle_wiring(message)
        return


# --------------------------------------------------------------------------- #
#  ۵) /daily و /help
# --------------------------------------------------------------------------- #
def _record_line(rec: dict[str, Any]) -> str:
    title = (
        rec.get("Name") or rec.get("نام") or rec.get("Title") or rec.get("عنوان") or "بدون عنوان"
    )
    status = rec.get("Status") or rec.get("وضعیت") or "—"
    edited = (rec.get("_last_edited") or "")[:10]
    url = rec.get("_url")
    line = f"• {title} — وضعیت: {status} — آخرین ویرایش: {edited or 'نامشخص'}"
    if url:
        line += f' — <a href="{url}">لینک</a>'
    return line


async def handle_daily(message: Message) -> None:
    """خلاصه کارهای روز همه ایجنت‌ها از Notion."""
    if not notion_service.available:
        await message.reply_text(
            "⚠️ Notion پیکربندی نشده است (NOTION_API_KEY خالی). خلاصه روزانه در دسترس نیست."
        )
        return

    status = await message.reply_text("📥 خواندن وضعیت روزانه از Notion…")
    data = await notion_service.fetch_daily_logs(settings.notion_db_map())

    lines: list[str] = [f"📊 <b>خلاصه وضعیت روز — {human_today(settings.display_timezone)}</b>", ""]

    for agent in registry.agents.values():
        records = data["by_agent"].get(agent.id) or []
        state = "فعال" if agent.enabled else "غیرفعال"
        lines.append(f"<b>{agent.id} — {agent.name}</b> ({state})")
        if not settings.notion_db_id(agent.id):
            lines.append("• دیتابیس Notion برای این ایجنت تنظیم نشده است → <i>نامشخص</i>")
        elif not records:
            lines.append("• هیچ رکوردی یافت نشد → <i>داده‌ای در دست نیست</i> (نه صفر، نه تأیید)")
        else:
            lines.extend(_record_line(r) for r in records[:5])
            if len(records) > 5:
                lines.append(f"• … و {len(records) - 5} رکورد دیگر")
        lines.append("")

    if data["daily_log"]:
        lines.append("<b>ثبت‌های daily_log (اخیر)</b>")
        for rec in data["daily_log"][:8]:
            agent = rec.get("Agent") or "—"
            mission = rec.get("Mission") or "—"
            day = rec.get("Date") or "—"
            lines.append(f"• {agent} | {day} | {str(mission)[:80]}")
        lines.append("")

    if data["errors"]:
        lines.append("<b>⚠️ خطاها</b>")
        lines.extend(f"• {err[:200]}" for err in data["errors"][:5])

    body = "\n".join(lines)
    chunks = split_for_telegram(body, limit=3900)
    if not chunks:
        chunks = ["داده‌ای برای نمایش نیست."]
    try:
        await status.edit_text(
            chunks[0], parse_mode=ParseMode.HTML, disable_web_page_preview=True
        )
    except BadRequest:
        await message.reply_text(
            chunks[0], parse_mode=ParseMode.HTML, disable_web_page_preview=True
        )
    for chunk in chunks[1:]:
        await message.reply_text(
            chunk, parse_mode=ParseMode.HTML, disable_web_page_preview=True
        )


async def handle_wiring(message: Message) -> None:
    """`/wiring` — عیب‌یابی اتصال Notion بدون نیاز به ترمینال."""
    lines = ["🔌 <b>وضعیت اتصال</b>\n"]

    # ۱) توکن و ربات
    lines.append(f"{'✅' if bot_ready else '❌'} ربات تلگرام")

    # ۲) کلید Notion
    lines.append(f"{'✅' if notion_service.available else '❌'} کلید Notion")

    # ۳) دیتابیس Tasks
    st = automation.status()
    if st["task_store_available"]:
        lines.append("✅ دیتابیس Tasks: متصل")
    elif not settings.notion_tasks_db:
        lines.append("❌ دیتابیس Tasks: NOTION_TASKS_DB خالی است")
        lines.append("   <i>در پیوی: /start → بخش اتوماسیون</i>")
    else:
        lines.append("❌ دیتابیس Tasks: دسترسی ندارد")
        lines.append("   <i>در Notion: ⋯ → Connections → integration را اضافه کنید</i>")

    # ۴) پولر
    lines.append(f"{'✅' if st['poller_running'] else '❌'} پولر Notion")
    stats = st["poller_stats"]
    if st["poller_running"]:
        lines.append(
            f"   <code>اسکن: {stats.get('scanned', 0)} | اجرا: {stats.get('executed', 0)} | "
            f"خطا: {stats.get('errors', 0)} | زنجیره: {stats.get('chains', 0)}</code>"
        )

    # ۵) بررسی زندهٔ دیتابیس Tasks (اگر متصل است)
    if automation.task_store is not None and automation.task_store.available:
        try:
            from services.tasks import runnable_statuses
            pending: list[dict] = []
            for ag in [f"AG{i:02d}" for i in range(1, 10)]:
                rows = await automation.task_store.query(assignee=ag, statuses=runnable_statuses(), limit=3)
                pending.extend(rows)
            if pending:
                lines.append(f"\n📋 <b>{len(pending)} وظیفهٔ آمادهٔ اجرا</b> (پولر می‌گیرد):")
                for r in pending[:5]:
                    lines.append(f"   • {r.get('Assignee')} — {str(r.get('Name'))[:40]}")
            else:
                lines.append(
                    "\n⚠️ <b>هیچ وظیفه‌ای در وضعیت اجرا نیست</b>\n"
                    f"   پولر دنبال وضعیت‌های: <code>{', '.join(runnable_statuses())}</code>\n"
                    "   در Notion یک رکورد با همین وضعیت بسازید یا: /task @ag01 تست"
                )
        except Exception as exc:  # noqa: BLE001
            lines.append(f"\n⚠️ خطا در خواندن Tasks: <code>{str(exc)[:120]}</code>")

    # ۶) سایر
    lines.append(f"{'✅' if llm_service.available else '❌'} OpenAI")
    lines.append(f"{'✅' if mongo._client is not None else '❌'} MongoDB")  # noqa: SLF001

    if not st["task_store_available"]:
        lines.append(
            "\n<b>راه‌حل سریع:</b>\n"
            "<code>./wiring.sh --tasks &lt;شناسهٔ-دیتابیس&gt;</code>\n"
            "یا در پیوی <code>/start</code>"
        )

    await message.reply_text(
        "\n".join(lines), parse_mode=ParseMode.HTML, disable_web_page_preview=True
    )


async def handle_tasks(message: Message) -> None:
    """`/tasks` — نمایش وظایف فعال، جدا برای ایجنت‌ها و انسان‌ها."""
    try:
        lines = ["🧩 <b>وضعیت وظایف</b>"]
        open_tasks = [t for t in automation.index.all() if t.status not in {"انجام شد", "رد شد"}]

        agent_tasks = [t for t in open_tasks if not t.is_human]
        human_tasks = [t for t in open_tasks if t.is_human]

        lines.append("\n<b>🤖 وظایف ایجنت‌ها</b>")
        if agent_tasks:
            for t in agent_tasks[:15]:
                icon = {"برای انجام": "📋", "در حال انجام": "🔄", "منتظر بازبینی": "👀"}.get(t.status, "•")
                lines.append(f"{icon} <b>{t.assignee}</b> — {t.title} [{t.status}]")
                if t.notion_url:
                    lines.append(f'   <a href="{t.notion_url}">Notion</a>')
        else:
            lines.append("  <i>وظیفهٔ بازی نیست.</i>")

        lines.append("\n<b>👤 وظایف انسان‌ها</b>")
        if human_tasks:
            for t in human_tasks[:15]:
                icon = {"برای انجام": "📋", "در حال انجام": "🔄", "منتظر بازبینی": "👀"}.get(t.status, "•")
                lines.append(f"{icon} <b>{t.assignee}</b> — {t.title} [{t.status}]")
        else:
            lines.append("  <i>وظیفهٔ انسانی بازی نیست.</i>")

        lines.append(
            "\n<code>/task @A03 عنوان</code> · <code>/task @H02 عنوان</code> · "
            "<code>/task @A01-A09 عنوان</code>"
        )

        st = automation.status()
        lines.append(
            f"\n<code>Notion: {'متصل' if st['task_store_available'] else 'تنظیم‌نشده'} | "
            f"پولر: {'فعال' if st['poller_running'] else 'خاموش'} | "
            f"اجراشده: {st['poller_stats'].get('executed', 0)}</code>"
        )
        await message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML,
                                 disable_web_page_preview=True)
    except Exception:  # noqa: BLE001
        logger.exception("نمایش وظایف ناموفق بود")
        await message.reply_text("⚠️ خطا در خواندن وظایف (لاگ سرور).")


async def handle_help(message: Message) -> None:
    from services.assignees import get_registry as _get_assignees

    _reg = _get_assignees()
    lines = [
        "<b>راهنمای ربات ایجنت‌ها</b>",
        "",
        "<b>منشن کن تا فقط همان ایجنت پاسخ دهد:</b>",
        "<code>@ag03 سؤال</code> — یا کوتاه: <code>@a03 سؤال</code>",
        "",
        "<b>وظیفه دادن — ۹ ایجنت + ۳ انسان:</b>",
        "<code>/task @A03 عنوان وظیفه</code>",
        "<code>/task @H02 کاری که برادر باید انجام دهد</code>",
        "<code>/task @A01-A09 عنوان</code> (۹ وظیفه)",
        "<code>/task @H01-H03 عنوان</code> (۳ وظیفه)",
        "<code>/task @A03,@H02 عنوان</code> (۲ وظیفه)",
        "<code>/task @agents عنوان</code> · <code>/task @humans عنوان</code>",
        "",
        "<b>ایجنت‌های موجود:</b>",
    ]
    for agent in registry.agents.values():
        flag = "" if agent.enabled else " <i>(غیرفعال)</i>"
        lines.append(f"• <code>{agent.mention}</code> — {agent.name}: {agent.role}{flag}")

    lines.append("")
    lines.append("<b>انسان‌ها (وظیفه می‌گیرند):</b>")
    for human in _reg.humans.values():
        lines.append(f"• <code>{human.id}</code> — {human.name}: {human.role}")

    lines += [
        "",
        "<code>/all سؤال…</code> — همه ایجنت‌های فعال پاسخ می‌دهند (هر کدام پیام جدا)",
        "<code>/daily</code> — خلاصه وضعیت روز همه ایجنت‌ها از Notion",
        "<code>/help</code> — همین راهنما",
        "",
        "پیام‌های بدون منشن فقط ذخیره می‌شوند و پاسخی نمی‌گیرند.",
    ]
    await message.reply_text("\n".join(lines), parse_mode=ParseMode.HTML)


# --------------------------------------------------------------------------- #
#  ۶) ساخت Application
# --------------------------------------------------------------------------- #
async def _post_init(application: Application) -> None:
    await application.bot.set_my_commands(
        [
            BotCommand("task", "ساخت وظیفه برای ایجنت یا انسان — /task @A03 عنوان"),
            BotCommand("tasks", "وضعیت وظایف ایجنت‌ها و انسان‌ها"),
            BotCommand("all", "همه ایجنت‌های فعال پاسخ می‌دهند"),
            BotCommand("daily", "خلاصه وضعیت روز از Notion"),
            BotCommand("wiring", "عیب‌یابی اتصال Notion"),
            BotCommand("help", "راهنما"),
            BotCommand("id", "نمایش شناسه کاربری من"),
        ]
    )
    logger.info("ربات آماده است: @%s", application.bot.username)


def build_application() -> Application:
    application = (
        Application.builder()
        .token(settings.telegram_bot_token)
        .rate_limiter(AIORateLimiter())
        .post_init(_post_init)
        .build()
    )
    # یک هندلر واحد برای همه پیام‌ها: ذخیره + روتینگ (منشن / /all / /daily / /help)
    # توجه: CommandHandler جداگانه اضافه نکنید، وگرنه پیام دوبار پردازش می‌شود.
    application.add_handler(
        MessageHandler(filters.ALL & ~filters.StatusUpdate.ALL, handle_message)
    )
    application.add_handler(CallbackQueryHandler(handle_callback_query))
    application.add_error_handler(_on_error)
    return application


async def _on_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
    """خطاهای رایج تلگرام → پیام فارسی کوتاه با راه‌حل."""
    exc = context.error
    name = type(exc).__name__
    text = str(exc)

    if "Conflict" in text or "terminated by other" in text:
        hint = (
            "⚠️ <b>تعارض polling</b>\n"
            "یک نسخهٔ دیگر از ربات (یا n8n) هم‌زمان polling می‌کند.\n"
            "<b>راه‌حل:</b>\n"
            "۱) <code>ps aux | grep bot.py</code> — نسخه‌های اضافی را ببندید\n"
            "۲) در n8n ورک‌فلوی <code>02-telegram-polling</code> را Active نکنید\n"
            "۳) یا وبهوک بگذارید: <code>./run.sh restart</code>"
        )
    elif "Forbidden" in text or "bot was blocked" in text:
        hint = "⚠️ ربات بلاک شده یا در گروه ادمین نیست."
    elif "Too Many Requests" in text or "RetryAfter" in text:
        hint = "⏳ محدودیت نرخ تلگرام — چند لحظه صبر کنید."
    elif "Message is too long" in text:
        hint = "⚠️ پاسخ بلندتر از ۴۰۹۶ کاراکتر شد."
    elif isinstance(exc, NetworkError):
        hint = "🌐 خطای شبکه — اتصال سرور به api.telegram.org بررسی شود."
    else:
        hint = f"⚠️ خطای غیرمنتظره: <code>{name}</code>"

    logger.error("خطا در پردازش آپدیت [%s]: %s", name, text[:300])

    msg = getattr(update, "effective_message", None)
    if msg is not None:
        try:
            await msg.reply_text(hint, parse_mode=ParseMode.HTML)
        except TelegramError:
            pass


# --------------------------------------------------------------------------- #
#  ۷) FastAPI + وب‌هوک
# --------------------------------------------------------------------------- #
telegram_app: Optional[Application] = None
bot_ready = False          # آیا Application با موفقیت initialize/start شده است
_bot_lock = asyncio.Lock()


def get_telegram_app() -> Application:
    global telegram_app
    if telegram_app is None:
        telegram_app = build_application()
    return telegram_app


TOKEN_HELP = (
    "راه‌حل:\n"
    "  ۱) توکن واقعی از @BotFather بگیرید (شکل: 123456789:AAH…۳۵ کاراکتر)\n"
    "  ۲) در .env بگذارید:  TELEGRAM_BOT_TOKEN=<توکن>\n"
    "     یا در ترمینال:      ./run.sh token <توکن>\n"
    "  ۳) سپس: ./run.sh start --polling"
)


def token_problem() -> str | None:
    """بررسی اعتبار ظاهری توکن؛ متن مشکل یا None."""
    token = (settings.telegram_bot_token or "").strip()
    if not token:
        return "TELEGRAM_BOT_TOKEN خالی است (نه در .env و نه در دیتابیس)."
    if "xxx" in token.lower() or token.startswith("123456789:"):
        return "TELEGRAM_BOT_TOKEN همان مقدار نمونهٔ .env.example است، نه توکن واقعی."
    if not re.match(r"^\d{6,}:[A-Za-z0-9_-]{30,}$", token):
        return "قالب TELEGRAM_BOT_TOKEN درست نیست (باید شبیه 123456789:AA… باشد)."
    return None


async def _polling_runner() -> int:
    """اجرای ربات با long-polling. کد خروج: 0 موفق، 2 خطای توکن."""
    await ensure_token_from_store()

    problem = token_problem()
    if problem:
        logger.error("%s\n%s", problem, TOKEN_HELP)
        return 2

    application = get_telegram_app()
    try:
        await application.initialize()
    except InvalidToken:
        logger.error(
            "تلگرام توکن را رد کرد (InvalidToken) — توکن باطل یا اشتباه است.\n%s",
            TOKEN_HELP,
        )
        return 2
    except TelegramError as exc:
        logger.error("اتصال به تلگرام برقرار نشد: %s", exc)
        return 3

    await application.start()
    await application.bot.delete_webhook(drop_pending_updates=settings.drop_pending_updates)
    await application.updater.start_polling(
        allowed_updates=Update.ALL_TYPES, drop_pending_updates=settings.drop_pending_updates
    )
    logger.info("✅ ربات در حالت POLLING اجرا شد. Ctrl+C برای توقف.")
    try:
        await asyncio.Event().wait()
    finally:
        await application.updater.stop()
        await application.stop()
        await application.shutdown()
    return 0


async def ensure_token_from_store() -> bool:
    """اگر توکن در .env نبود، از تنظیمات ذخیره‌شده (ویزارد) خوانده می‌شود."""
    if settings.telegram_bot_token and not token_problem():
        return True
    try:
        await mongo.connect(settings.mongodb_uri, settings.mongodb_db)
        saved = await config_store.load_overrides(
            settings.mongodb_db, settings.mongo_config_collection
        )
        if saved:
            apply_saved_config(saved)
            refresh_services()
    except Exception:  # noqa: BLE001
        logger.warning("خواندن توکن از دیتابیس ممکن نشد.")
    return bool(settings.telegram_bot_token)


async def _startup() -> None:
    """اتصال دیتابیس/سرویس‌ها، راه‌اندازی Application و ثبت وب‌هوک."""
    global bot_ready

    if not settings.telegram_bot_token:
        await ensure_token_from_store()

    if not settings.telegram_bot_token:
        logger.error(
            "TELEGRAM_BOT_TOKEN خالی است؛ ربات راه‌اندازی نمی‌شود (سرور بالا می‌ماند). "
            "توکن را در .env بگذارید یا با ویزارد پیوی ذخیره کنید."
        )
        return

    try:
        await mongo.connect(settings.mongodb_uri, settings.mongodb_db)
        # تنظیمات ذخیره‌شده از ویزارد، بر .env اولویت دارد
        saved = await config_store.load_overrides(
            settings.mongodb_db, settings.mongo_config_collection
        )
        if saved:
            apply_saved_config(saved)
            refresh_services()
    except Exception:  # noqa: BLE001 — نبود دیتابیس نباید سرور را بخواباند
        logger.exception("مقداردهی MongoDB/تنظیمات با خطا مواجه شد؛ ادامه می‌دهیم.")

    application = get_telegram_app()
    try:
        await application.initialize()
        await application.start()
    except InvalidToken:
        logger.error(
            "تلگرام توکن را رد کرد (InvalidToken). %s\n"
            "سرور FastAPI بالا می‌ماند (bot_ready=false) تا ویزارد/سلامت قابل بررسی باشد.\n%s",
            "توکن باطل یا مقدار نمونه است.",
            TOKEN_HELP,
        )
        return
    except TelegramError as exc:
        logger.error(
            "راه‌اندازی ربات ناموفق بود (%s). TELEGRAM_BOT_TOKEN را بررسی کنید. "
            "سرور FastAPI بالا می‌ماند تا /health قابل بررسی باشد.",
            exc,
        )
        return

    bot_ready = True
    # پولر Notion: وظایفی که از داخل Notion ساخته/منشن می‌شوند
    try:
        if settings.notion_poller_enabled and automation.start_poller():
            logger.info(
                "پولر Notion فعال شد (هر %s ثانیه) — دیتابیس Tasks: %s",
                settings.notion_poll_seconds,
                "متصل" if automation.task_store and automation.task_store.available else "تنظیم‌نشده",
            )
    except Exception:  # noqa: BLE001
        logger.exception("راه‌اندازی پولر Notion ناموفق بود")

    if os.getenv("POLLING"):
        try:
            await application.bot.delete_webhook(drop_pending_updates=False)
            logger.info("حالت polling: وب‌هوک قبلی حذف شد (جلوگیری از 409 Conflict).")
        except TelegramError as exc:
            logger.warning("حذف وب‌هوک قبلی ناموفق بود (%s) — ادامه می‌دهیم.", exc)
        return

    try:
        await application.bot.set_webhook(
            url=settings.webhook_url,
            secret_token=settings.telegram_webhook_secret,
            allowed_updates=Update.ALL_TYPES,
            drop_pending_updates=settings.drop_pending_updates,
        )
        logger.info("وب‌هوک ثبت شد: %s", settings.webhook_url)
    except TelegramError as exc:
        logger.error(
            "ثبت وب‌هوک ناموفق بود (%s).\n"
            "  PUBLIC_BASE_URL فعلی: %r\n"
            "  راه‌حل: دامنه HTTPS عمومی بگذارید (https://bot.example.com) یا حالت polling را انتخاب کنید: ./run.sh start --polling",
            exc,
            settings.public_base_url,
        )


async def _shutdown() -> None:
    global telegram_app, bot_ready
    bot_ready = False
    try:
        await automation.stop_poller()
    except Exception:  # noqa: BLE001
        logger.debug("توقف پولر Notion با هشدار تمام شد", exc_info=True)
    if telegram_app is not None:
        try:
            if telegram_app.running:
                await telegram_app.stop()
            await telegram_app.shutdown()
        except Exception as exc:  # noqa: BLE001 — خاموشی نباید خطای زشت بدهد
            logger.warning("خاموش‌کردن Application با هشدار تمام شد: %s", exc)
    await notion_service.aclose()
    await llm_service.aclose()
    await mongo.close()


@asynccontextmanager
async def lifespan(_: FastAPI):
    await _startup()
    try:
        yield
    finally:
        await _shutdown()


app = FastAPI(
    title="Telegram AI Agents Bot",
    version="1.0.0",
    description="ربات گروه تلگرام با ۹ ایجنت هوش مصنوعی، Notion و MongoDB",
    lifespan=lifespan,
)


def _assignee_registry():
    """رجیستری گیرندگان (ایجنت + انسان)."""
    from services.assignees import get_registry

    return get_registry()


@app.get("/")
async def root() -> dict[str, Any]:
    return {
        "status": "ok",
        "service": "telegram-ai-agents",
        "bot_ready": bot_ready,
        "setup_wizard": settings.setup_wizard_enabled,
        "admins_configured": len(settings.allowed_ids()) + len(settings.allowed_usernames()),
        "agents": [
            {"id": a.id, "name": a.name, "enabled": a.enabled} for a in registry.agents.values()
        ],
    }


@app.get("/health")
async def health() -> dict[str, Any]:
    return {
        "ok": True,
        "bot_ready": bot_ready,
        "mongodb": mongo._client is not None,  # noqa: SLF001 — بررسی ساده وضعیت
        "notion": notion_service.available,
        "llm": llm_service.available,
        "daily_log_enabled": bool(settings.notion_daily_log_db),
        "notion_databases_configured": sum(
            1 for agent_id in registry.agents if settings.notion_db_id(agent_id)
        ),
        "version": settings.app_version,
        "sources": {
            "configured": {k: bool(v) for k, v in settings.source_dbs.items()},
            "sheets": sheet_cache.status(),
        },
        "assignees": {
            "agents": [a.id for a in registry.agents.values()],
            "humans": {
                code: h.name for code, h in _assignee_registry().humans.items()
            },
        },
        "setup_wizard": settings.setup_wizard_enabled,
        "admins_configured": len(settings.allowed_ids()) + len(settings.allowed_usernames()),
        "webhook": settings.webhook_url,
        "webhook_url_valid": bool(
            settings.public_base_url.startswith("https://")
            and "your-domain" not in settings.public_base_url
            and "example.com" not in settings.public_base_url
        ),
        "mode": "polling" if os.getenv("POLLING") else "webhook",
        "automation": automation.status(),
    }


async def ensure_bot_running() -> bool:
    """اگر توکن بعد از استارت‌اپ ست شده باشد (از ویزارد/دیتابیس)، ربات را دیرتر بالا می‌آورد."""
    global bot_ready
    if bot_ready:
        return True
    if not settings.telegram_bot_token:
        return False
    async with _bot_lock:
        if bot_ready:
            return True
        try:
            application = get_telegram_app()
            await application.initialize()
            await application.start()
            bot_ready = True
            logger.info("ربات به‌صورت دیرهنگام راه‌اندازی شد (توکن از تنظیمات ذخیره‌شده).")
        except InvalidToken:
            logger.error("راه‌اندازی دیرهنگام ناموفق: توکن رد شد (InvalidToken).\n%s", TOKEN_HELP)
            return False
        except TelegramError as exc:
            logger.error("راه‌اندازی دیرهنگام ربات ناموفق بود: %s", exc)
            return False
    return True


@app.post(settings.webhook_path)
async def telegram_webhook(
    request: Request,
    x_telegram_bot_api_secret_token: str | None = Header(default=None),
) -> dict[str, bool]:
    if x_telegram_bot_api_secret_token != settings.telegram_webhook_secret:
        raise HTTPException(status_code=403, detail="secret token نامعتبر است")
    if not settings.telegram_bot_token and not await ensure_token_from_store():
        raise HTTPException(status_code=503, detail="توکن ربات تنظیم نشده است")
    await ensure_bot_running()

    payload = await request.json()
    application = get_telegram_app()
    update = Update.de_json(payload, application.bot)
    try:
        async with _bot_lock:
            await application.process_update(update)
    except TelegramError as exc:
        # پاسخ به تلگرام با 200 داده می‌شود تا update دوباره ارسال نشود
        logger.error("پردازش update ناموفق بود: %s", exc)
    return {"ok": True}


# --------------------------------------------------------------------------- #
#  اندپوینت داخلی دریافت Google Sheets از n8n
# --------------------------------------------------------------------------- #
def _is_loopback(request: Request) -> bool:
    """آیا درخواست از همان ماشین آمده؟"""
    host = (request.client.host if request.client else "") or ""
    return host in {"127.0.0.1", "::1", "localhost"}


@app.post("/internal/sheets/push")
async def sheets_push(
    request: Request,
    payload: dict[str, Any],
    x_internal_token: str | None = Header(default=None),
) -> dict[str, Any]:
    """دریافت شش تب Sheets از n8n و نگه‌داری در حافظه.

    امنیت: توکن مشترک (INTERNAL_TOKEN) + محدودیت loopback به‌صورت پیش‌فرض.
    """
    if not settings.internal_token:
        raise HTTPException(
            status_code=503,
            detail="INTERNAL_TOKEN تنظیم نشده است. با ./run.sh set INTERNAL_TOKEN <مقدار> تنظیم کنید.",
        )
    if (x_internal_token or "") != settings.internal_token:
        logger.warning("پوش Sheets با توکن نامعتبر رد شد از %s", request.client)
        raise HTTPException(status_code=401, detail="توکن داخلی نامعتبر است")
    if not settings.sheets_push_allow_remote and not _is_loopback(request):
        raise HTTPException(
            status_code=403,
            detail="فقط از همان سرور. برای اجازهٔ شبکه، SHEETS_PUSH_ALLOW_REMOTE=true کنید.",
        )

    count = sheet_cache.update(payload)
    return {"ok": True, "tabs": count, "last_sync": sheet_cache.last_sync}


@app.get("/internal/sheets/status")
async def sheets_status(x_internal_token: str | None = Header(default=None)) -> dict[str, Any]:
    """وضعیت کش Sheets — برای عیب‌یابی n8n."""
    if settings.internal_token and (x_internal_token or "") != settings.internal_token:
        raise HTTPException(status_code=401, detail="توکن داخلی نامعتبر است")
    return sheet_cache.status()


@app.post("/set-webhook")
async def set_webhook(request: Request) -> dict[str, Any]:
    """ثبت دستی وب‌هوک (اختیاری، برای عیب‌یابی)."""
    body: dict[str, Any] = {}
    try:
        body = await request.json()
    except Exception:  # noqa: BLE001
        pass
    url = body.get("url") or settings.webhook_url
    try:
        await get_telegram_app().bot.set_webhook(
            url=url,
            secret_token=settings.telegram_webhook_secret,
            allowed_updates=Update.ALL_TYPES,
        )
    except TelegramError as exc:
        raise HTTPException(status_code=502, detail=f"ثبت وب‌هوک ناموفق: {exc}") from exc
    return {"ok": True, "url": url}


def main() -> None:
    if any(arg in {"--diagnose", "--doctor", "doctor"} for arg in sys.argv[1:]):
        from services.diagnostics import main as diagnose

        sys.exit(diagnose())

    # توکن ممکن است در .env نباشد ولی قبلاً با ویزارد در دیتابیس ذخیره شده باشد
    if token_problem():
        asyncio.run(ensure_token_from_store())

    problem = token_problem()
    if problem:
        logger.error("%s\n%s", problem, TOKEN_HELP)
        sys.exit(2)

    if os.getenv("POLLING"):
        sys.exit(asyncio.run(_polling_runner()))
    else:
        uvicorn.run(
            "bot:app",
            host=settings.host,
            port=settings.port,
            log_level=settings.log_level.lower(),
            proxy_headers=True,
            forwarded_allow_ips="*",
        )


if __name__ == "__main__":
    main()
