"""
HTTP Client for API requests

Handles authentication, error handling, and common HTTP operations.
"""

import requests
from typing import Optional, Dict, Any, Tuple
from . import config


class APIError(Exception):
    """API request error"""
    pass


class APIClient:
    """HTTP client for Veloz API"""
    
    def __init__(self, server_url: Optional[str] = None):
        self.server_url = server_url or config.get_server_url()
        self.session = requests.Session()
        
        # Development mode: skip SSL verification
        if config.is_development_mode():
            self.session.verify = False
            import urllib3
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    def _get_headers(self, authenticated: bool = False) -> Dict[str, str]:
        """Get request headers"""
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': 'VelozCLI/1.0.0'
        }
        
        if authenticated:
            creds = config.load_credentials()
            if not creds:
                raise APIError('Not logged in. Run `veloz login` first.')
            
            headers['Authorization'] = f'Bearer {creds["token"]}'
        
        return headers
    
    def get(self, endpoint: str, authenticated: bool = True) -> Tuple[int, Dict[str, Any]]:
        """
        Make GET request.
        
        Returns:
            (status_code, response_data)
        """
        url = f"{self.server_url}{endpoint}"
        headers = self._get_headers(authenticated)
        
        try:
            response = self.session.get(url, headers=headers, timeout=30)
            return response.status_code, response.json()
        except requests.exceptions.RequestException as e:
            raise APIError(f'Network error: {e}')
        except ValueError as e:
            raise APIError(f'Invalid JSON response from server')
    
    def post(self, endpoint: str, data: Optional[Dict] = None, 
             authenticated: bool = True, files: Optional[Dict] = None) -> Tuple[int, Dict[str, Any]]:
        """
        Make POST request.
        
        Returns:
            (status_code, response_data)
        """
        url = f"{self.server_url}{endpoint}"
        headers = self._get_headers(authenticated)
        
        try:
            if files:
                # Remove Content-Type for multipart
                headers.pop('Content-Type', None)
                response = self.session.post(url, headers=headers, files=files, timeout=120)
            else:
                response = self.session.post(url, headers=headers, json=data, timeout=30)
            
            return response.status_code, response.json()
        except requests.exceptions.RequestException as e:
            raise APIError(f'Network error: {e}')
        except ValueError as e:
            raise APIError(f'Invalid JSON response from server')
    
    def delete(self, endpoint: str, authenticated: bool = True) -> Tuple[int, Dict[str, Any]]:
        """
        Make DELETE request.
        
        Returns:
            (status_code, response_data)
        """
        url = f"{self.server_url}{endpoint}"
        headers = self._get_headers(authenticated)
        
        try:
            response = self.session.delete(url, headers=headers, timeout=30)
            return response.status_code, response.json()
        except requests.exceptions.RequestException as e:
            raise APIError(f'Network error: {e}')
        except ValueError:
            raise APIError('Invalid JSON response from server')

