"""Configuration management for MCP standalone server."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Final

try:
    import tomllib  # Python 3.11+
except ImportError:
    import tomli as tomllib  # type: ignore[import-not-found]

__all__ = ["MCPConfig", "get_gfp_api_key", "set_gfp_api_key"]


class MCPConfig:
    """Configuration for MCP standalone server.

    Manages environment variables and default settings for the MCP server
    that proxies requests to the FastAPI backend.
    """

    API_URL: Final[str | None] = os.getenv("GFP_API_URL")

    TIMEOUT: Final[int] = int(os.getenv("GFP_MCP_TIMEOUT", "300"))

    DEBUG: Final[bool] = os.getenv("GFP_MCP_DEBUG", "false").lower() in (
        "true",
        "1",
        "yes",
    )

    REGISTRY_API_URL: Final[str] = "https://registry.gdsfactory.com"

    MAX_RETRIES: Final[int] = 3
    RETRY_BACKOFF: Final[float] = 0.5  # Initial backoff in seconds

    @classmethod
    def get_api_url(cls, override: str | None = None) -> str | None:
        """Get the FastAPI base URL.

        Args:
            override: Optional URL to override the environment variable

        Returns:
            The API base URL or None if not configured
        """
        return override or cls.API_URL

    @classmethod
    def get_timeout(cls) -> int:
        """Get the timeout for tool calls.

        Returns:
            Timeout in seconds
        """
        return cls.TIMEOUT


def _read_api_key_from_toml(file_path: Path) -> str | None:
    """Read the API key from a TOML configuration file.

    Args:
        file_path: Path to the TOML file.

    Returns:
        The API key string, or None if not found or file doesn't exist.
    """
    if not file_path.exists():
        return None

    try:
        with open(file_path, "rb") as f:
            config = tomllib.load(f)

        return (
            config.get("tool", {}).get("gdsfactoryplus", {}).get("api", {}).get("key")
        )
    except Exception:
        return None


def get_gfp_api_key() -> str | None:
    """Retrieve the GFP API key from environment variables or config files.

    Checks sources in priority order:
    1. GFP_API_KEY environment variable
    2. ~/.gdsfactory/gdsfactoryplus.toml
    3. ./pyproject.toml

    Returns:
        The API key string, or None if not found.
    """
    # 1. Check environment variable (highest priority)
    api_key = os.environ.get("GFP_API_KEY")
    if api_key:
        return api_key

    # 2. Check global config file: ~/.gdsfactory/gdsfactoryplus.toml
    global_config_path = Path.home() / ".gdsfactory" / "gdsfactoryplus.toml"
    api_key = _read_api_key_from_toml(global_config_path)
    if api_key:
        return api_key

    # 3. Check local project config: ./pyproject.toml
    local_config_path = Path.cwd() / "pyproject.toml"
    api_key = _read_api_key_from_toml(local_config_path)
    if api_key:
        return api_key

    return None


def set_gfp_api_key(api_key: str) -> None:
    """Save the GFP API key to the global config file.

    Writes to: ~/.gdsfactory/gdsfactoryplus.toml

    Args:
        api_key: The API key to save.

    Raises:
        ValueError: If api_key is empty or None.
    """
    if not api_key:
        raise ValueError("API key is required")

    config_dir = Path.home() / ".gdsfactory"
    config_path = config_dir / "gdsfactoryplus.toml"

    # Create directory if it doesn't exist
    config_dir.mkdir(parents=True, exist_ok=True)

    # Load existing config or create new one
    config: dict = {}
    if config_path.exists():
        with open(config_path, "rb") as f:
            config = tomllib.load(f)

    # Set the API key in the nested structure
    if "tool" not in config:
        config["tool"] = {}
    if "gdsfactoryplus" not in config["tool"]:
        config["tool"]["gdsfactoryplus"] = {}
    if "api" not in config["tool"]["gdsfactoryplus"]:
        config["tool"]["gdsfactoryplus"]["api"] = {}

    config["tool"]["gdsfactoryplus"]["api"]["key"] = api_key

    # Write back to file using tomli_w if available, otherwise manual formatting
    try:
        import tomli_w

        with open(config_path, "wb") as f:
            tomli_w.dump(config, f)
    except ImportError:
        # Fallback: write TOML manually for this simple structure
        with open(config_path, "w") as f:
            f.write("[tool.gdsfactoryplus.api]\n")
            f.write(f'key = "{api_key}"\n')
