import requests

class VecsaiClient:
    def __init__(self, host="localhost", port=8137):
        self.base_url = f"http://{host}:{port}"
        self.headers = {"Content-Type": "application/json"}

    def health(self):
        """curl http://localhost:8137/health"""
        return requests.get(f"{self.base_url}/health").json()

    def create_collection(self, schema):
        """Koleksiyon oluşturma"""
        url = f"{self.base_url}/collections"
        return requests.post(url, json=schema, headers=self.headers).json()

    def add_document(self, collection_name, document):
        """Tekil doküman ekleme"""
        url = f"{self.base_url}/collections/{collection_name}/documents"
        return requests.post(url, json=document, headers=self.headers).json()

    def upload_csv(self, collection_name, file_path, action="create"):
        """
        Görseldeki endpoint: multipart/form-data kullanarak CSV yükler.
        """
        url = f"{self.base_url}/collections/{collection_name}/documents/upload"
        params = {"action": action, "format": "csv"}
        
        with open(file_path, 'rb') as f:
            files = {'file': f}
            # requests, files parametresi verildiğinde Content-Type'ı 
            # otomatik olarak multipart/form-data yapar.
            response = requests.post(url, params=params, files=files)
        
        return response.json()

    def search(self, collection_name, q, query_by, filter_by=None):
        """Arama ve filtreleme"""
        url = f"{self.base_url}/collections/{collection_name}/documents/search"
        params = {'q': q, 'query_by': query_by}
        if filter_by:
            params['filter_by'] = filter_by
            
        return requests.get(url, params=params).json()