import requests
import logging
from typing import Dict, Optional, Any

logger = logging.getLogger(__name__)

class SSLAPIClient:
    """
    Client to interact with the SSL Auto-Renewal Service API.
    """
    def __init__(self, api_url: str, api_key: Optional[str] = None, timeout: int = 30):
        self.api_url = api_url.rstrip('/')
        self.timeout = timeout
        self.headers = {}
        if api_key:
            self.headers['X-API-Key'] = api_key

    def validate_certificate(self, domain: str, auto_renew: bool = True) -> Dict[str, Any]:
        """
        Ask the central service to validate (and optionally renew) the certificate.
        """
        url = f"{self.api_url}/validate"
        payload = {
            "domain": domain,
            "auto_renew": auto_renew
        }
        
        try:
            response = requests.post(url, json=payload, headers=self.headers, timeout=self.timeout)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            logger.error(f"Failed to validate certificate for {domain}: {e}")
            raise

    def get_certificate_files(self, domain: str) -> Dict[str, Any]:
        """
        Download the certificate files content (JSON) from the central service.
        """
        url = f"{self.api_url}/certificate/{domain}/files"
        
        try:
            response = requests.post(url, headers=self.headers, timeout=self.timeout)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            logger.error(f"Failed to get certificate files for {domain}: {e}")
            raise

