from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Protocol
import os

try:
    import keyring
except Exception:
    keyring = None


@dataclass(frozen=True)
class IdentityToken:
    token: str


class TokenProvider(Protocol):
    def get(self) -> Optional[IdentityToken]: ...


class EnvTokenProvider:
    def __init__(self, env_var: str = "AIEL_TOKEN"):
        self.env_var = env_var

    def get(self) -> Optional[IdentityToken]:
        t = os.getenv(self.env_var)
        return IdentityToken(t) if t else None


class KeyringTokenProvider:
    def __init__(self, service: str = "aiel", username: str = "default"):
        self.service = service
        self.username = username

    def get(self) -> Optional[IdentityToken]:
        if keyring is None:
            return None
        t = keyring.get_password(self.service, self.username)
        return IdentityToken(t) if t else None


class ProviderChain:
    def __init__(self, providers: list[TokenProvider]):
        self.providers = providers

    def resolve(self) -> IdentityToken:
        for p in self.providers:
            tok = p.get()
            if tok and tok.token:
                return tok
        raise RuntimeError(
            "No identity token found. Set AIEL_TOKEN (recommended for Cloud Run), "
            "or run `aiel auth login` locally (keyring)."
        )


def default_chain() -> ProviderChain:
    return ProviderChain([EnvTokenProvider(), KeyringTokenProvider()])
