import uuid
from datetime import datetime, timezone
from pymongo.asynchronous.database import AsyncDatabase

async def get_active_conversation_by_session_id(db: AsyncDatabase, session_id: str) -> dict | None:
    cursor = db["conversations"].find({
        "sessionId": session_id,
        "status": {"$nin": ["ended", "ENDED"]}
    }).sort("createdAt", -1)
    results = await cursor.to_list(length=1)
    return results[0] if results else None

async def get_conversation_by_session_id(db: AsyncDatabase, session_id: str) -> dict | None:
    cursor = db["conversations"].find({"sessionId": session_id}).sort("createdAt", -1)
    results = await cursor.to_list(length=1)
    return results[0] if results else None

async def get_conversation_by_id(db: AsyncDatabase, conversation_id: str) -> dict | None:
    return await db["conversations"].find_one({"conversationId": conversation_id})

async def get_or_create_conversation(db: AsyncDatabase, session_id: str, site_id: str) -> dict:
    active_conv = await get_active_conversation_by_session_id(db, session_id)
    if active_conv:
        return active_conv
        
    latest_conv = await get_conversation_by_session_id(db, session_id)
    if latest_conv and latest_conv.get("status") not in ("ended", "ENDED"):
        return latest_conv
        
    conv_id = f"conv_{uuid.uuid4().hex[:12]}"
    now = datetime.now(timezone.utc)
    
    conv_doc = {
        "conversationId": conv_id,
        "sessionId": session_id,
        "siteId": site_id,
        "status": "open",
        "createdAt": now,
        "updatedAt": now
    }
    
    await db["conversations"].insert_one(conv_doc)
    return conv_doc
