"""Env-var-based factory functions for storage clients."""

from __future__ import annotations

import os

from storage_core.clients.s3 import S3StorageClient
from storage_core.serializer import MetadataSerializer

# Default env-var prefixes (RustFS-first, then generic S3/AWS)
_S3_ENDPOINT_VARS = ("RUSTFS_ENDPOINT_URL", "S3_ENDPOINT_URL")
_S3_ACCESS_KEY_VARS = ("RUSTFS_ACCESS_KEY", "AWS_ACCESS_KEY_ID")
_S3_SECRET_KEY_VARS = ("RUSTFS_SECRET_KEY", "AWS_SECRET_ACCESS_KEY")
_S3_REGION_VARS = ("RUSTFS_REGION", "S3_REGION", "AWS_DEFAULT_REGION")


def _first_env(*names: str) -> str | None:
    """Return the value of the first set environment variable, or ``None``."""
    for name in names:
        val = os.environ.get(name)
        if val:
            return val
    return None


def create_s3_storage_client(
    endpoint_url: str | None = None,
    access_key: str | None = None,
    secret_key: str | None = None,
    *,
    region: str | None = None,
    metadata_serializer: MetadataSerializer | None = None,
    secure: bool | None = None,
) -> S3StorageClient:
    """Create an :class:`~storage_core.clients.s3.S3StorageClient`.

    Parameters are resolved from environment variables when not explicitly
    provided, in this order:

    * **endpoint_url**: ``RUSTFS_ENDPOINT_URL`` → ``S3_ENDPOINT_URL``
    * **access_key**: ``RUSTFS_ACCESS_KEY`` → ``AWS_ACCESS_KEY_ID``
    * **secret_key**: ``RUSTFS_SECRET_KEY`` → ``AWS_SECRET_ACCESS_KEY``
    * **region**: ``RUSTFS_REGION`` → ``S3_REGION`` → ``AWS_DEFAULT_REGION`` → ``"us-east-1"``
    """
    return S3StorageClient(
        endpoint_url=endpoint_url or _first_env(*_S3_ENDPOINT_VARS) or "",
        access_key=access_key or _first_env(*_S3_ACCESS_KEY_VARS) or "",
        secret_key=secret_key or _first_env(*_S3_SECRET_KEY_VARS) or "",
        region=region or _first_env(*_S3_REGION_VARS) or "us-east-1",
        metadata_serializer=metadata_serializer,
        secure=secure,
    )


# Convenience alias
get_s3_storage_client = create_s3_storage_client
