"""Configuration management for manta-client CLI.

Configuration file location: ~/.manta/config.toml
"""

from __future__ import annotations

import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import rtoml

# Environment-specific API endpoints
_PROD_API_URL = "http://10.100.36.169:8000"
_DEV_API_URL = "http://10.100.36.190:8000"


def _is_dev_version() -> bool:
    """Check if the current client is a dev (non-release) version."""
    try:
        from manta_client._version import __version__
    except ModuleNotFoundError:
        return True
    return "dev" in __version__


def _default_api_url() -> str:
    """Return default API URL based on client version."""
    return _DEV_API_URL if _is_dev_version() else _PROD_API_URL


@dataclass
class MantaConfig:
    """Manta client configuration."""

    api_url: str = ""
    access_token: str = ""
    refresh_token: str = ""
    session_uuid: str = ""
    user_id: str = ""
    username: str = ""

    def __post_init__(self) -> None:
        """Resolve empty api_url to version-aware default."""
        if not self.api_url:
            self.api_url = _default_api_url()

    def to_dict(self) -> dict[str, Any]:
        """Convert config to dictionary."""
        return {
            "api_url": self.api_url,
            "access_token": self.access_token,
            "refresh_token": self.refresh_token,
            "session_uuid": self.session_uuid,
            "user_id": self.user_id,
            "username": self.username,
        }

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> MantaConfig:
        """Create config from dictionary."""
        return cls(
            api_url=data.get("api_url", ""),
            access_token=data.get("access_token", ""),
            refresh_token=data.get("refresh_token", ""),
            session_uuid=data.get("session_uuid", ""),
            user_id=data.get("user_id", ""),
            username=data.get("username", ""),
        )


@dataclass
class ConfigManager:
    """Configuration manager for manta-client."""

    config_dir: Path = field(
        default_factory=lambda: Path(os.environ.get("MANTA_CONFIG_DIR", Path.home() / ".manta"))
    )
    config_file: str = "config.toml"

    @property
    def config_path(self) -> Path:
        """Get full path to config file."""
        return self.config_dir / self.config_file

    def ensure_config_dir(self) -> None:
        """Ensure config directory exists."""
        self.config_dir.mkdir(parents=True, exist_ok=True)

    def load_config(self) -> MantaConfig:
        """Load configuration from file."""
        if not self.config_path.exists():
            return MantaConfig()

        try:
            content = self.config_path.read_text(encoding="utf-8")
            data = rtoml.loads(content)
            # Get the default profile
            default_data = data.get("default", {})
            return MantaConfig.from_dict(default_data)
        except Exception:
            return MantaConfig()

    def save_config(self, config: MantaConfig) -> None:
        """Save configuration to file."""
        self.ensure_config_dir()
        data = {"default": config.to_dict()}
        content = rtoml.dumps(data)
        self.config_path.write_text(content, encoding="utf-8")

    def get_token(self) -> str:
        """Get current access token."""
        config = self.load_config()
        return config.access_token

    def set_token(self, token: str, session_uuid: str = "") -> None:
        """Set access token."""
        config = self.load_config()
        config.access_token = token
        config.session_uuid = session_uuid
        self.save_config(config)

    def clear_auth(self) -> None:
        """Clear authentication information."""
        config = self.load_config()
        config.access_token = ""
        config.refresh_token = ""
        config.session_uuid = ""
        config.user_id = ""
        config.username = ""
        self.save_config(config)

    def set_value(self, key: str, value: str) -> bool:
        """Set a configuration value.

        Args:
            key: Configuration key (e.g., 'api_url')
            value: Configuration value

        Returns:
            True if successful, False if key is invalid
        """
        config = self.load_config()
        if not hasattr(config, key):
            return False

        setattr(config, key, value)
        self.save_config(config)
        return True

    def get_value(self, key: str) -> str | None:
        """Get a configuration value.

        Args:
            key: Configuration key

        Returns:
            Configuration value or None if key is invalid
        """
        config = self.load_config()
        if not hasattr(config, key):
            return None
        return getattr(config, key)


# Global config manager instance
config_manager = ConfigManager()


def get_config() -> MantaConfig:
    """Get current configuration."""
    return config_manager.load_config()


def save_config(config: MantaConfig) -> None:
    """Save configuration."""
    config_manager.save_config(config)
