import os
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from config import get_config

config = get_config()
client: AsyncIOMotorClient | None = None
chat_col = None
users_col = None

async def init_db():
    global client, db, chat_col, users_col
    client = AsyncIOMotorClient(
        config.get("MONGO_URI"),
        maxPoolSize=100,
        minPoolSize=4,
        serverSelectionTimeoutMS=10000,
        tls=False,
        uuidRepresentation='standard',
        tz_aware=True,
        retryWrites=True,
    )
    db = client[config.get("DB_NAME")]
    chat_col = db[config.get("COLLECTION_CHAT")]
    users_col = db[config.get("COLLECTION_USERS")]
    
async def shutdown_db():
    global client
    if client is not None:
        client.close()
        client = None

def get_db_client() -> AsyncIOMotorClient:
    assert client is not None, "Mongo client henüz başlatılmadı."
    return client

def get_collections():
    assert chat_col is not None and users_col is not None
    return chat_col, users_col

async def ensure_indexes() -> None:
    chat_col, users_col = get_collections()
    await asyncio.gather(
        users_col.create_index("isim"),
        chat_col.create_index([("thread_id", 1), ("timestamp", 1)]),
        chat_col.create_index("role"),
    )

async def save_message(thread_id: str, role: str, message: str) -> None:
    from datetime import datetime
    chat_col, _ = get_collections()
    await chat_col.insert_one({
        "thread_id": thread_id,
        "role": role,
        "message": message,
        "timestamp": datetime.now(),
    })