"""
API configuration service.

Loads and validates API configuration from ~/.czbg/.env file.
Follows CLAUDE.md: Single responsibility, <10 methods, <50 lines/method.
"""

from dataclasses import dataclass
from typing import Optional

from src.services.environment_service import EnvironmentService


@dataclass
class APIConfig:
    """API configuration from environment variables."""

    api_url: str
    api_key: Optional[str] = None
    timeout: int = 300  # 5 minutes default


class ConfigService:
    """
    Load and validate API configuration.

    Single responsibility: API configuration management.
    Uses EnvironmentService to read from ~/.czbg/.env file.
    """

    def __init__(self):
        """Initialize config service with environment service."""
        self.env_service = EnvironmentService()

    def get_api_config(self) -> APIConfig:
        """
        Load API configuration from ~/.czbg/.env file.

        Environment variables:
        - CZBG_API_URL: Lambda API endpoint (required)
        - CZBG_API_KEY: API key for authentication (optional)
        - CZBG_API_TIMEOUT: Request timeout in seconds (optional, default 300)

        Returns:
            APIConfig instance

        Raises:
            ValueError: If CZBG_API_URL is not set in ~/.czbg/.env
        """
        api_url = self.env_service.require(
            "CZBG_API_URL",
            "CZBG_API_URL is required for API mode. "
            "Add it to your ~/.czbg/.env file with the Lambda API endpoint URL."
        )

        api_key = self.env_service.get("CZBG_API_KEY")
        timeout = int(self.env_service.get("CZBG_API_TIMEOUT", "300"))

        return APIConfig(api_url=api_url, api_key=api_key, timeout=timeout)

    def validate_api_config(self, config: APIConfig) -> bool:
        """
        Validate API configuration.

        Args:
            config: API configuration to validate

        Returns:
            True if valid

        Raises:
            ValueError: If configuration is invalid
        """
        if not config.api_url:
            raise ValueError("API URL cannot be empty")

        if not config.api_url.startswith(("http://", "https://")):
            raise ValueError("API URL must start with http:// or https://")

        if config.timeout <= 0:
            raise ValueError("API timeout must be positive")

        return True
