import json
import os
from bson import json_util
from typing import Type
from pydantic import BaseModel, Field
from langchain.tools import BaseTool

import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)));

from db import get_collections

class MongoDBToolInput(BaseModel):
    name: str = Field(default="all", description="Sorgu bilgisi. 'all' ile tüm kullanıcılar listelenir. 'alan:değer' ile filtrelenir.")

class MongoDBTool(BaseTool):
    name: str = "mongodb_kullanici_sorgula"
    description: str = "MongoDB'den belirtilen kritere göre kullanıcı sorgular."
    args_schema: Type[BaseModel] = MongoDBToolInput

    async def _arun(self, name: str = "all") -> str:
        _, users_col = get_collections()
        if not name or name.lower() in {"all","hepsi","tamamı"}:
            cursor = users_col.find({}, projection={"_id": 0}).max_time_ms(3000)
        elif ":" in name:
            field, value = map(str.strip, name.split(":", 1))
            cursor = users_col.find({field: value}, projection={"_id": 0}).max_time_ms(3000)
        else:
            cursor = users_col.find({"isim": name}, projection={"_id": 0}).max_time_ms(3000)
        data = [doc async for doc in cursor.limit(1000)]
        return json_util.dumps(data, ensure_ascii=False)

    async def _run(self, name: str = "all") -> str:
        return await self._arun(name)