import httpx from typing import Optional from config import config class DirectusClient: def __init__(self, url: Optional[str] = None, token: Optional[str] = None): self.url = (url or config.DIRECTUS_URL).rstrip("/") self.token = token or config.DIRECTUS_TOKEN self._client = httpx.Client( base_url=self.url, headers={ "Authorization": f"Bearer {self.token}", "Content-Type": "application/json", }, timeout=30, ) def is_available(self) -> bool: try: resp = self._client.get("/server/ping") return resp.status_code == 200 except Exception: return False def create_call(self, data: dict, collection: str = "calls") -> Optional[dict]: try: resp = self._client.post(f"/items/{collection}", json=data) if resp.status_code in (200, 201): return resp.json().get("data") return None except Exception: return None def update_call(self, call_id: str, data: dict) -> bool: try: resp = self._client.patch(f"/items/calls?filter[call_id][_eq]={call_id}", json=data) return resp.status_code in (200, 201) except Exception: return False def find_contact(self, phone_number: str) -> Optional[dict]: try: resp = self._client.get( "/items/contacts", params={"filter[phone_number][_eq]": phone_number, "limit": 1}, ) if resp.status_code == 200: data = resp.json().get("data", []) if data: return data[0] return None except Exception: return None def create_contact(self, data: dict) -> Optional[dict]: try: resp = self._client.post("/items/contacts", json=data) if resp.status_code in (200, 201): return resp.json().get("data") return None except Exception: return None def update_contact(self, contact_id: str, data: dict) -> bool: try: resp = self._client.patch(f"/items/contacts/{contact_id}", json=data) return resp.status_code in (200, 201) except Exception: return False def close(self): self._client.close()