"""اتصال به MongoDB — ذخیره و خواندن تاریخچه چت گروه."""

from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any, Optional

from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection
from pymongo import ASCENDING, DESCENDING, IndexModel

logger = logging.getLogger(__name__)

_client: Optional[AsyncIOMotorClient] = None


async def connect(uri: str, db_name: str) -> None:
    """برقراری اتصال (تنبل تا اولین عملیات) و ساخت ایندکس‌ها.

    خطای اتصال باعث کرش ربات نمی‌شود؛ فقط لاگ می‌شود تا سرور بالا بماند.
    """
    global _client
    _client = AsyncIOMotorClient(uri, tz_aware=True, serverSelectionTimeoutMS=5000)
    try:
        await _client.admin.command("ping")
        collection = get_history_collection(db_name)
        await collection.create_indexes(
            [
                IndexModel([("chat_id", ASCENDING), ("date", DESCENDING)]),
                IndexModel([("chat_id", ASCENDING), ("message_id", ASCENDING)], unique=True),
            ]
        )
        logger.info("MongoDB connected (db=%s)", db_name)
    except Exception as exc:  # noqa: BLE001
        logger.error(
            "اتصال به MongoDB ناموفق بود (%s). ربات بالا می‌ماند ولی پیام‌ها ذخیره نمی‌شوند.",
            exc,
        )


async def close() -> None:
    global _client
    if _client is not None:
        _client.close()
        _client = None
        logger.info("MongoDB connection closed")


def get_history_collection(db_name: str, collection: str = "chat_history") -> AsyncIOMotorCollection:
    if _client is None:
        raise RuntimeError("MongoDB در دسترس نیست؛ ابتدا connect() را صدا بزنید.")
    return _client[db_name][collection]


async def save_message(doc: dict[str, Any], db_name: str, collection: str = "chat_history") -> None:
    """ذخیره یک پیام؛ در صورت تکرار message_id (مثلاً retry وبهوک) نادیده گرفته می‌شود."""
    col = get_history_collection(db_name, collection)
    doc.setdefault("date", datetime.now(timezone.utc))
    doc.setdefault("saved_at", datetime.now(timezone.utc))
    try:
        await col.insert_one(dict(doc))
    except Exception as exc:  # DuplicateKeyError یا خطای موقت
        if "duplicate key" in str(exc).lower():
            logger.debug("پیام تکراری نادیده گرفته شد: %s", doc.get("message_id"))
        else:
            logger.exception("خطا در ذخیره پیام: %s", exc)


async def get_last_messages(
    chat_id: int, limit: int = 30, db_name: str = "tg_agents", collection: str = "chat_history"
) -> list[dict[str, Any]]:
    """آخرین N پیام گروه به ترتیب قدیمی → جدید."""
    col = get_history_collection(db_name, collection)
    cursor = col.find({"chat_id": chat_id}).sort("date", DESCENDING).limit(limit)
    rows = await cursor.to_list(length=limit)
    rows.reverse()
    return rows


async def get_last_messages_since(
    chat_id: int, since: datetime, db_name: str, collection: str = "chat_history"
) -> list[dict[str, Any]]:
    """پیام‌های یک بازه زمانی (برای خلاصه روزانه)."""
    col = get_history_collection(db_name, collection)
    cursor = col.find({"chat_id": chat_id, "date": {"$gte": since}}).sort("date", ASCENDING)
    return await cursor.to_list(length=2000)
