"""Credential storage using OS keyring with graceful fallback."""
from __future__ import annotations

import logging

logger = logging.getLogger("dattos_sdk")

_SERVICE_PREFIX = "dattos-cli"

try:
    import keyring as _keyring
    _keyring_available = True
except ImportError:
    _keyring_available = False


def _service_name(profile: str) -> str:
    return f"{_SERVICE_PREFIX}/{profile}"


def _keyring_set(service: str, username: str, password: str) -> None:
    _keyring.set_password(service, username, password)


def _keyring_get(service: str, username: str) -> str | None:
    return _keyring.get_password(service, username)


def _keyring_delete(service: str, username: str) -> None:
    try:
        _keyring.delete_password(service, username)
    except Exception:
        pass


def store_secret(profile: str, key: str, value: str) -> bool:
    """Store a secret in the OS keyring. Returns True on success."""
    if not _keyring_available:
        return False
    try:
        _keyring_set(_service_name(profile), key, value)
        return True
    except Exception as e:
        logger.debug("Keyring store failed: %s", e)
        return False


def get_secret(profile: str, key: str) -> str | None:
    """Get a secret from the OS keyring. Returns None if unavailable."""
    if not _keyring_available:
        return None
    try:
        return _keyring_get(_service_name(profile), key)
    except Exception as e:
        logger.debug("Keyring get failed: %s", e)
        return None


def delete_secret(profile: str, key: str) -> None:
    """Delete a secret from the OS keyring."""
    if not _keyring_available:
        return
    try:
        _keyring_delete(_service_name(profile), key)
    except Exception as e:
        logger.debug("Keyring delete failed: %s", e)
