from __future__ import annotations

import keyring
from keyring.backend import KeyringBackend

from cli.keychain import get_api_key, store_api_key


class InMemoryKeyring(KeyringBackend):
    """Simple keyring backend for tests."""

    priority = 1

    def __init__(self) -> None:
        self._storage: dict[tuple[str, str], str] = {}

    def get_password(self, service: str, username: str) -> str | None:
        return self._storage.get((service, username))

    def set_password(self, service: str, username: str, password: str) -> None:
        self._storage[(service, username)] = password

    def delete_password(self, service: str, username: str) -> None:
        self._storage.pop((service, username), None)


def test_store_and_retrieve_api_key(monkeypatch):
    backend = InMemoryKeyring()
    keyring.set_keyring(backend)

    api_key = "ctxme_" + ("A" * 32)
    store_api_key(api_key)

    assert get_api_key() == api_key
