"""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 save_credentials(api_key: str, base_url: str) -> pathlib.Path:
    """Save credentials to ``~/.keiro/credentials``.

    Returns:
        The path written to.
    """
    CREDENTIALS_PATH.parent.mkdir(parents=True, exist_ok=True)
    CREDENTIALS_PATH.write_text(
        f"api_key: {api_key}\nbase_url: {base_url}\n"
    )
    try:
        CREDENTIALS_PATH.chmod(0o600)
    except OSError:
        # Best-effort on platforms/filesystems that do not support POSIX perms.
        pass
    return CREDENTIALS_PATH
