"""Configuration management for the AppXen CLI.

Stores API key and endpoint in ~/.config/appxen/config.toml with 0o600 perms.
Supports multiple profiles and env var overrides.
"""

from __future__ import annotations

import os
import sys
from dataclasses import dataclass
from pathlib import Path

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib

import tomli_w

DEFAULT_ENDPOINT = "https://api.appxen.ai"
CONFIG_DIR = Path.home() / ".config" / "appxen"
CONFIG_FILE = CONFIG_DIR / "config.toml"


@dataclass
class Profile:
    """A single CLI profile."""

    api_key: str
    endpoint: str = DEFAULT_ENDPOINT


def _active_profile_name() -> str:
    return os.environ.get("APPXEN_PROFILE", "default")


def load_profile(profile: str | None = None) -> Profile | None:
    """Load a profile from config file, with env var overrides."""
    name = profile or _active_profile_name()

    # Env vars take highest priority
    env_key = os.environ.get("APPXEN_API_KEY")
    env_endpoint = os.environ.get("APPXEN_ENDPOINT")

    if env_key:
        return Profile(
            api_key=env_key,
            endpoint=env_endpoint or DEFAULT_ENDPOINT,
        )

    if not CONFIG_FILE.exists():
        return None

    with open(CONFIG_FILE, "rb") as f:
        data = tomllib.load(f)

    section = data.get(name)
    if not section or "api_key" not in section:
        return None

    return Profile(
        api_key=section["api_key"],
        endpoint=section.get("endpoint", DEFAULT_ENDPOINT),
    )


def save_profile(
    api_key: str,
    endpoint: str = DEFAULT_ENDPOINT,
    profile: str | None = None,
) -> None:
    """Save a profile to config file."""
    name = profile or _active_profile_name()

    CONFIG_DIR.mkdir(parents=True, exist_ok=True)

    data: dict = {}
    if CONFIG_FILE.exists():
        with open(CONFIG_FILE, "rb") as f:
            data = tomllib.load(f)

    section = {"api_key": api_key, "endpoint": endpoint}
    data[name] = section

    with open(CONFIG_FILE, "wb") as f:
        tomli_w.dump(data, f)

    # Secure permissions (owner read/write only)
    CONFIG_FILE.chmod(0o600)
