from __future__ import annotations

from typing import Optional

import keyring

from .base import SecretStorage


class KeyringSecretStorage(SecretStorage):
    """Secret storage backed by the system keyring."""

    def set_secret(self, service: str, key: str, value: str) -> None:
        keyring.set_password(service, key, value)

    def get_secret(self, service: str, key: str) -> Optional[str]:
        return keyring.get_password(service, key)

    def delete_secret(self, service: str, key: str) -> None:
        try:
            keyring.delete_password(service, key)
        except keyring.errors.PasswordDeleteError:
            # Secret not present; nothing to remove.
            return
