"""Configuration management for flukebase_connect client."""

import os
import socket
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

_tomli = None
_logger = None
_cached_config = None

DEV_HOST = "localhost"
DEV_PORT = 3006
DEV_API_URL = f"http://{DEV_HOST}:{DEV_PORT}/api/v1"
PROD_API_URL = "https://flukebase.me/api/v1"


def _get_logger():
    """Get logger, importing logging module lazily."""
    global _logger
    if _logger is None:
        import logging
        _logger = logging.getLogger(__name__)
    return _logger


def _detect_api_url() -> str:
    """Auto-detect API URL: prefer localhost dev server if available."""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((DEV_HOST, DEV_PORT))
        sock.close()

        if result == 0:
            return DEV_API_URL
    except Exception:
        pass

    return PROD_API_URL


@dataclass
class FlukeBaseConfig:
    """FlukeBase API configuration."""

    api_url: str = field(default_factory=_detect_api_url)
    api_token: Optional[str] = None
    current_project_id: Optional[int] = None


@dataclass
class Config:
    """Main configuration for flukebase_connect client."""

    home: Path = field(default_factory=lambda: Path.home() / ".flukebase-connect")
    flukebase: FlukeBaseConfig = field(default_factory=FlukeBaseConfig)

    def __post_init__(self):
        """Ensure home directory exists."""
        self.home.mkdir(parents=True, exist_ok=True)

    @classmethod
    def load(cls, use_cache: bool = True) -> "Config":
        """Load configuration from environment and config files."""
        global _cached_config

        if use_cache and _cached_config is not None:
            return _cached_config

        config = cls()

        # Load from config file
        config_file = config.home / "config.toml"
        if config_file.exists():
            global _tomli
            if _tomli is None:
                try:
                    import tomli as _tomli_mod
                    _tomli = _tomli_mod
                except ImportError:
                    _tomli = False

            if _tomli:
                with open(config_file, "rb") as f:
                    data = _tomli.load(f)

                if "flukebase" in data:
                    fb_config = data["flukebase"]
                    if "api_url" in fb_config:
                        config.flukebase.api_url = fb_config["api_url"]
                    if "api_token" in fb_config:
                        config.flukebase.api_token = fb_config["api_token"]

        # Environment variables override config file
        if os.environ.get("FLUKEBASE_API_URL"):
            config.flukebase.api_url = os.environ["FLUKEBASE_API_URL"]
        if os.environ.get("FLUKEBASE_API_TOKEN"):
            config.flukebase.api_token = os.environ["FLUKEBASE_API_TOKEN"]

        if use_cache:
            _cached_config = config

        return config

    def save(self):
        """Save configuration to config file."""
        config_file = self.home / "config.toml"

        content = f"""[flukebase]
api_url = "{self.flukebase.api_url}"
"""
        if self.flukebase.api_token:
            content += f'api_token = "{self.flukebase.api_token}"\n'

        config_file.write_text(content)


def clear_config_cache() -> None:
    """Clear the cached config singleton."""
    global _cached_config
    _cached_config = None


def get_config() -> Config:
    """Get the cached config singleton."""
    return Config.load()
