"""Keiro credential storage — stdlib only, no external dependencies.

Credentials live at ``~/.keiro/credentials`` in a trivial ``key: value``
format. Both ``keiro setup`` (write) and ``KeirProvider`` (read) use this
module, keeping the credential pipeline independent of ember internals.
"""

from __future__ import annotations

import pathlib

CREDENTIALS_PATH = pathlib.Path.home() / ".keiro" / "credentials"


def load_credentials() -> dict[str, str]:
    """Load credentials from ``~/.keiro/credentials``.

    Returns:
        Dict with ``api_key`` and/or ``base_url`` keys, or empty dict
        if the file does not exist.
    """
    if not CREDENTIALS_PATH.exists():
        return {}
    result: dict[str, str] = {}
    for line in CREDENTIALS_PATH.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        key, _, value = line.partition(":")
        if value:
            result[key.strip()] = value.strip()
    return result


def _write_credentials(creds: dict[str, str]) -> None:
    """Write credentials dict to ``~/.keiro/credentials``."""
    CREDENTIALS_PATH.parent.mkdir(parents=True, exist_ok=True)
    CREDENTIALS_PATH.write_text(
        "".join(f"{k}: {v}\n" for k, v in creds.items()),
    )
    try:
        CREDENTIALS_PATH.chmod(0o600)
    except OSError:
        pass


def _update_credentials(updates: dict[str, str | None]) -> pathlib.Path:
    """Read-modify-write credentials. ``None`` values remove the key."""
    creds = load_credentials()
    for key, value in updates.items():
        if value is None:
            creds.pop(key, None)
        else:
            creds[key] = value
    _write_credentials(creds)
    return CREDENTIALS_PATH


def save_credentials(api_key: str, base_url: str) -> pathlib.Path:
    """Save credentials, preserving any existing admin settings."""
    return _update_credentials({"api_key": api_key, "base_url": base_url})


def save_admin_token(token: str) -> pathlib.Path:
    """Add or update the admin token in credentials.

    .. deprecated::
        Admin access is now determined by the API key role segment.
        Use an API key with the ``admin`` role instead of a separate
        admin token. This function will be removed in a future release.
    """
    import warnings

    warnings.warn(
        "save_admin_token is deprecated. Use an API key with admin "
        "role (key:org:tier:admin) instead of a separate admin token.",
        DeprecationWarning,
        stacklevel=2,
    )
    return _update_credentials({"admin_token": token})


def clear_admin_token() -> pathlib.Path:
    """Remove the admin token from credentials."""
    return _update_credentials({"admin_token": None})


def set_admin_mode(enabled: bool) -> None:
    """Persist the admin mode toggle."""
    _update_credentials({"admin_mode": "on" if enabled else None})


def is_admin_mode() -> bool:
    """Return True if admin mode is persistently enabled."""
    return load_credentials().get("admin_mode") == "on"
