from __future__ import annotations

from dataclasses import dataclass
from threading import Lock

from .store import CredentialStore


@dataclass(slots=True)
class ProviderCredential:
    provider: str
    credential_ref: str
    scope: str
    key_preview: str | None


class ProviderPoolV2:
    """Org-scoped credential pool that will replace ProviderPool (Phase 1.5)."""

    def __init__(self, store: CredentialStore) -> None:
        self._store = store
        self._lock = Lock()

    def acquire(self, org_id: str, provider: str) -> str | None:
        """Return the credential reference for the given org/provider if available."""

        with self._lock:
            candidates = self._store.list(org_id=org_id, provider=provider)
            for cred in candidates:
                if cred.status == "active":
                    return cred.credential_ref
            # Fallback to resell pool (org_id None)
            resell = self._store.list(org_id=None, provider=provider)
            for cred in resell:
                if cred.status == "active":
                    return cred.credential_ref
        return None


__all__ = ["ProviderPoolV2", "ProviderCredential"]
