"""
ID Wispera Keychain Provider
Optional OS keychain integration for secure passphrase storage.

Uses `keyring` when available (macOS Keychain, Windows Credential Manager,
Linux Secret Service). Degrades gracefully — returns None if keyring is
not installed or the OS keychain is unavailable.
"""

from typing import Optional

SERVICE_NAME = "id-wispera"
ACCOUNT_NAME = "vault-passphrase"

try:
    import keyring

    _KEYRING_AVAILABLE = True
except ImportError:
    _KEYRING_AVAILABLE = False


class KeychainProvider:
    """Thin wrapper around the OS keychain via the ``keyring`` library."""

    def is_available(self) -> bool:
        """Whether the keychain backend is available on this system."""
        if not _KEYRING_AVAILABLE:
            return False
        try:
            # Smoke-test to verify a usable backend is configured
            keyring.get_password(SERVICE_NAME, "__probe__")
            return True
        except Exception:
            return False

    def store(self, passphrase: str) -> bool:
        """
        Store the vault passphrase in the OS keychain.
        Returns True on success, False if the keychain is unavailable.
        """
        if not _KEYRING_AVAILABLE:
            return False
        try:
            keyring.set_password(SERVICE_NAME, ACCOUNT_NAME, passphrase)
            return True
        except Exception:
            return False

    def retrieve(self) -> Optional[str]:
        """
        Retrieve the vault passphrase from the OS keychain.
        Returns None if unavailable or no entry exists.
        """
        if not _KEYRING_AVAILABLE:
            return None
        try:
            return keyring.get_password(SERVICE_NAME, ACCOUNT_NAME)
        except Exception:
            return None

    def remove(self) -> bool:
        """
        Remove the vault passphrase from the OS keychain.
        Returns True if deleted, False if unavailable or nothing to delete.
        """
        if not _KEYRING_AVAILABLE:
            return False
        try:
            keyring.delete_password(SERVICE_NAME, ACCOUNT_NAME)
            return True
        except Exception:
            return False
