"""Thin wrapper around keyring for API key storage."""

from __future__ import annotations

import sys

import keyring
from keyring.errors import KeyringError, PasswordDeleteError

from shared import validate_api_key_format

from .exceptions import KeyringFailure

SERVICE_NAME = "ctxme"
ACCOUNT_NAME = "api_key"


def _hint() -> str:
    if sys.platform.startswith("linux"):
        return (
            "Ensure a keyring backend (e.g., gnome-keyring or KWallet) is installed and unlocked."
        )
    if sys.platform == "darwin":
        return "Verify the login Keychain is unlocked."
    if sys.platform.startswith("win"):
        return "Check that the Windows Credential Manager service is running."
    return "Confirm an OS keychain backend is available."


def store_api_key(api_key: str) -> None:
    """Persist API key in the OS keychain."""
    validated = validate_api_key_format(api_key)
    try:
        keyring.set_password(SERVICE_NAME, ACCOUNT_NAME, validated)
    except KeyringError as exc:
        raise KeyringFailure(f"Unable to store API key in the OS keychain. {_hint()}") from exc


def get_api_key() -> str | None:
    """Retrieve stored API key, if any."""
    try:
        return keyring.get_password(SERVICE_NAME, ACCOUNT_NAME)
    except KeyringError as exc:
        raise KeyringFailure(f"Unable to read API key from the OS keychain. {_hint()}") from exc


def delete_api_key() -> None:
    """Remove the stored API key (best-effort)."""
    try:
        keyring.delete_password(SERVICE_NAME, ACCOUNT_NAME)
    except PasswordDeleteError:
        # Already removed or missing.
        return
    except KeyringError as exc:
        raise KeyringFailure(f"Unable to delete API key from the OS keychain. {_hint()}") from exc
