"""
Configuration management.

Stores PREFERENCES only, never credentials.
Credentials are managed by native CLIs (tsh, apollo-cli, docker).
"""

from pathlib import Path
from dataclasses import dataclass, field, asdict
from typing import Optional
import json

# Config location
CONFIG_DIR = Path.home() / ".esai"
CONFIG_FILE = CONFIG_DIR / "config.json"


@dataclass
class TeleportConfig:
    """Teleport preferences (no credentials stored - just preferences)."""
    proxy: str = "edgescaleai.teleport.sh:443"
    cluster: str = "edgescaleai.teleport.sh"
    auth_method: Optional[str] = None  # None = username/password, "okta" = Okta SSO
    username: Optional[str] = None  # For username/password login (username only, not password)


@dataclass
class ApolloConfig:
    """Apollo CLI preferences (no credentials)."""
    configured: bool = False


@dataclass
class DockerConfig:
    """Docker registry preferences (no credentials)."""
    registry: str = "edgescaleai.palantirapollo.com"


@dataclass
class Config:
    """
    User configuration - preferences only, NO credentials.

    Credentials are stored by:
    - Teleport: ~/.tsh/
    - Apollo CLI: its own config location
    - Docker: ~/.docker/config.json
    """
    teleport: TeleportConfig = field(default_factory=TeleportConfig)
    apollo: ApolloConfig = field(default_factory=ApolloConfig)
    docker: DockerConfig = field(default_factory=DockerConfig)
    setup_complete: bool = False

    def to_dict(self) -> dict:
        return {
            "teleport": asdict(self.teleport),
            "apollo": asdict(self.apollo),
            "docker": asdict(self.docker),
            "setup_complete": self.setup_complete,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "Config":
        config = cls()
        if "teleport" in data:
            config.teleport = TeleportConfig(**data["teleport"])
        if "apollo" in data:
            config.apollo = ApolloConfig(**data["apollo"])
        if "docker" in data:
            config.docker = DockerConfig(**data["docker"])
        config.setup_complete = data.get("setup_complete", False)
        return config


def load_config() -> Config:
    """Load config from file, or return defaults."""
    if CONFIG_FILE.exists():
        try:
            data = json.loads(CONFIG_FILE.read_text())
            return Config.from_dict(data)
        except Exception:
            pass
    return Config()


def save_config(config: Config) -> None:
    """Save config to file."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(config.to_dict(), indent=2))
