"""CLI authentication storage for API keys and credentials.

Stores API key and URL in ~/.alloy-runtime/config file for persistent authentication.
"""

import os
from pathlib import Path


CONFIG_DIR = Path.home() / ".alloy-runtime"
CONFIG_FILE = CONFIG_DIR / "config"


def save_credentials(api_url: str, api_key: str) -> None:
    """Save API credentials to config file.

    Creates ~/.alloy-runtime/config with API URL and key.

    Args:
        api_url: API server base URL (e.g., http://localhost:8000)
        api_key: API authentication key

    Example:
        save_credentials("http://localhost:8000", "sk_live_abc123...")
    """
    CONFIG_DIR.mkdir(exist_ok=True, mode=0o700)  # Secure directory permissions

    with open(CONFIG_FILE, "w") as f:
        f.write(f"ALLOY_RUNTIME_API_URL={api_url}\n")
        f.write(f"ALLOY_RUNTIME_API_KEY={api_key}\n")

    # Set secure file permissions (owner read/write only)
    os.chmod(CONFIG_FILE, 0o600)


def load_credentials() -> tuple[str, str] | None:
    """Load API credentials from config file.

    Returns:
        Tuple of (api_url, api_key) if config exists, None otherwise

    Example:
        creds = load_credentials()
        if creds:
            api_url, api_key = creds
    """
    if not CONFIG_FILE.exists():
        return None

    config: dict[str, str] = {}
    with open(CONFIG_FILE, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or "=" not in line:
                continue
            key, value = line.split("=", 1)
            config[key] = value

    if "ALLOY_RUNTIME_API_URL" in config and "ALLOY_RUNTIME_API_KEY" in config:
        return config["ALLOY_RUNTIME_API_URL"], config["ALLOY_RUNTIME_API_KEY"]

    return None


def clear_credentials() -> None:
    """Remove stored credentials (logout).

    Deletes the config file if it exists.
    """
    if CONFIG_FILE.exists():
        CONFIG_FILE.unlink()
