from typing import Any

import httpx
from common_logging import get_logger, log_performance

logger = get_logger(__name__)


class PlatformClient:

    def __init__(self, base_url: str='http://localhost:8000'):
        self.base_url = base_url
        self.client = httpx.AsyncClient(base_url=base_url, timeout=30.0)

    @log_performance(logger, threshold_ms=2000)
    async def search_knowledge(self, query: str, tenant_id: int) -> dict[str, Any]:
        try:
            response = await self.client.post('/api/v1/knowledge/search', json={'query': query, 'tenant_id': tenant_id})
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.warning("platform API call failed", endpoint="knowledge/search", tenant_id=tenant_id, error=str(e))
            raise

    @log_performance(logger, threshold_ms=2000)
    async def extract_graph(self, text: str, tenant_id: int) -> dict[str, Any]:
        try:
            response = await self.client.post('/api/v1/graph/extract', json={'text': text, 'tenant_id': tenant_id})
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.warning("platform API call failed", endpoint="graph/extract", tenant_id=tenant_id, error=str(e))
            raise

    @log_performance(logger, threshold_ms=2000)
    async def rag_query(self, question: str, tenant_id: int) -> dict[str, Any]:
        try:
            response = await self.client.post('/api/v1/rag/query', json={'question': question, 'tenant_id': tenant_id})
            response.raise_for_status()
            return response.json()
        except Exception as e:
            logger.warning("platform API call failed", endpoint="rag/query", tenant_id=tenant_id, error=str(e))
            raise

    async def close(self):
        await self.client.aclose()
platform_client = PlatformClient()
