"""Factory helpers to obtain the appropriate licence store."""

from __future__ import annotations

import logging
import os

from .database import LicenseDatabase
from .postgres_store import PostgresLicenseStore

logger = logging.getLogger(__name__)


def build_license_store():
    """Return the licence store configured for the current environment.

    Preference order:
    1. PostgreSQL if WEB_SENTINEL_POSTGRES_URL (or DATABASE_URL) is set and backend
       is not forced to sqlite.
    2. SQLite (legacy) otherwise.
    """

    backend = os.getenv("WEB_SENTINEL_LICENSE_BACKEND", "auto").lower()
    postgres_url = os.getenv("WEB_SENTINEL_POSTGRES_URL") or os.getenv("DATABASE_URL")

    if backend in {"postgresql", "auto"} and postgres_url:
        try:
            return PostgresLicenseStore(postgres_url)
        except Exception:
            logger.exception("Impossible d'initialiser le stockage de licences PostgreSQL.")
            if backend == "postgresql":
                raise

    return LicenseDatabase()
