"""Configuration management for sed.sh SDK."""

import os
import json
from pathlib import Path
from typing import Optional, Dict, Any


class Config:
    """Configuration manager for sed.sh SDK.

    Supports loading configuration from:
    1. Direct parameters
    2. Environment variables
    3. Config file (~/.sedsh/config.json)

    Priority order: parameters > environment > config file
    """

    DEFAULT_BASE_URL = "https://api.sed.sh"
    DEFAULT_TIMEOUT = 30
    CONFIG_DIR = Path.home() / ".sedsh"
    CONFIG_FILE = CONFIG_DIR / "config.json"

    @classmethod
    def load(
        cls,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        timeout: Optional[int] = None,
    ) -> Dict[str, Any]:
        """Load configuration from all sources.

        Args:
            api_key: API key (overrides env and config file)
            base_url: API base URL (overrides env and config file)
            timeout: Request timeout in seconds (overrides config file)

        Returns:
            Configuration dictionary

        Raises:
            ValueError: If API key is not found in any source
        """
        config: Dict[str, Any] = {}

        # Load from config file (lowest priority)
        file_config = cls._load_from_file()
        config.update(file_config)

        # Load from environment variables (medium priority)
        env_config = cls._load_from_env()
        config.update(env_config)

        # Apply direct parameters (highest priority)
        if api_key is not None:
            config["api_key"] = api_key
        if base_url is not None:
            config["base_url"] = base_url
        if timeout is not None:
            config["timeout"] = timeout

        # Set defaults
        config.setdefault("base_url", cls.DEFAULT_BASE_URL)
        config.setdefault("timeout", cls.DEFAULT_TIMEOUT)

        # Validate API key
        if "api_key" not in config:
            raise ValueError(
                "API key not found. Please provide it via:\n"
                "1. Constructor parameter: SedSH(api_key='...')\n"
                "2. Environment variable: SEDSH_API_KEY\n"
                "3. Config file: ~/.sedsh/config.json"
            )

        return config

    @classmethod
    def _load_from_file(cls) -> Dict[str, Any]:
        """Load configuration from config file.

        Returns:
            Configuration dictionary (empty if file doesn't exist)
        """
        if not cls.CONFIG_FILE.exists():
            return {}

        try:
            with open(cls.CONFIG_FILE, "r") as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            # Silently ignore malformed or unreadable config files
            return {}

    @classmethod
    def _load_from_env(cls) -> Dict[str, Any]:
        """Load configuration from environment variables.

        Supported variables:
        - SEDSH_API_KEY: API key
        - SEDSH_BASE_URL: API base URL

        Returns:
            Configuration dictionary
        """
        config: Dict[str, Any] = {}

        api_key = os.environ.get("SEDSH_API_KEY")
        if api_key:
            config["api_key"] = api_key

        base_url = os.environ.get("SEDSH_BASE_URL")
        if base_url:
            config["base_url"] = base_url

        return config

    @classmethod
    def save_to_file(cls, api_key: str, base_url: Optional[str] = None) -> None:
        """Save configuration to config file.

        Args:
            api_key: API key to save
            base_url: Optional custom base URL

        Raises:
            IOError: If unable to create config directory or write file
        """
        cls.CONFIG_DIR.mkdir(parents=True, exist_ok=True)

        config = {"api_key": api_key}
        if base_url:
            config["base_url"] = base_url

        with open(cls.CONFIG_FILE, "w") as f:
            json.dump(config, f, indent=2)
