"""
FastAPI Backend Client Wrapper

This module provides a client for calling the DcisionAI FastAPI backend.
It maintains loose coupling - the MCP server calls the backend via HTTP.
"""

import aiohttp
import json
from typing import Dict, Any, Optional
from .config import MCPConfig


class DcisionAIClient:
    """Client for DcisionAI FastAPI backend"""
    
    def __init__(self):
        self.base_url = MCPConfig.get_api_url()
        self.api_key = MCPConfig.get_api_key()
        self.timeout = aiohttp.ClientTimeout(total=MCPConfig.get_timeout())
    
    async def _make_request(
        self,
        method: str,
        endpoint: str,
        data: Optional[Dict[str, Any]] = None,
        params: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """Make HTTP request to FastAPI backend"""
        url = f"{self.base_url}{endpoint}"
        headers = {"Content-Type": "application/json"}
        
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        
        async with aiohttp.ClientSession(timeout=self.timeout) as session:
            async with session.request(
                method=method,
                url=url,
                headers=headers,
                json=data,
                params=params
            ) as response:
                response.raise_for_status()
                return await response.json()
    
    async def optimize(self, problem_description: str) -> Dict[str, Any]:
        """
        Run full optimization workflow
        
        Args:
            problem_description: Natural language problem description
            
        Returns:
            Optimization results
        """
        return await self._make_request(
            method="POST",
            endpoint="/api/optimize",
            data={"problem": problem_description}
        )
    
    async def optimize_async(self, problem_description: str) -> Dict[str, Any]:
        """
        Start async optimization workflow
        
        Args:
            problem_description: Natural language problem description
            
        Returns:
            Session ID and initial status
        """
        return await self._make_request(
            method="POST",
            endpoint="/api/optimize-async",
            data={"problem": problem_description}
        )
    
    async def get_async_status(self, session_id: str) -> Dict[str, Any]:
        """
        Get status of async optimization
        
        Args:
            session_id: Session ID from optimize_async
            
        Returns:
            Current status and results (if complete)
        """
        return await self._make_request(
            method="GET",
            endpoint=f"/api/async-status/{session_id}"
        )
    
    async def get_models(self) -> Dict[str, Any]:
        """Get list of deployed models"""
        return await self._make_request(
            method="GET",
            endpoint="/api/models"
        )
    
    async def optimize_with_model(self, model_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Run optimization with deployed model
        
        Args:
            model_id: Deployed model ID
            data: Model-specific input data
            
        Returns:
            Optimization results
        """
        return await self._make_request(
            method="POST",
            endpoint=f"/api/models/{model_id}/optimize",
            data=data
        )
    
    async def health_check(self) -> Dict[str, Any]:
        """Check backend health"""
        return await self._make_request(
            method="GET",
            endpoint="/health"
        )

