from __future__ import annotations

"""Utilities for normalizing Appwrite endpoints configured via environment variables."""

from functools import lru_cache

from src.core.config import get_settings


def normalize_appwrite_endpoint(endpoint: str | None, database_id: str | None = None) -> str | None:
    """Return a sanitized Appwrite endpoint without collection-specific paths.

    Deployments may configure ``APPWRITE_ENDPOINT`` with a full Databases URL such as
    ``https://nyc.cloud.appwrite.io/v1/databases/APPWRITE_DATABASE_ID``. This helper
    strips any ``/databases/<id>`` suffix and replaces placeholder occurrences of
    ``APPWRITE_DATABASE_ID`` with the provided database identifier so downstream code
    always works with a clean base endpoint.
    """

    if not isinstance(endpoint, str):
        return None

    trimmed = endpoint.strip()
    if not trimmed:
        return None

    normalized = trimmed.rstrip("/")
    if database_id:
        normalized = normalized.replace("APPWRITE_DATABASE_ID", database_id)

    marker = "/databases/"
    marker_index = normalized.find(marker)
    if marker_index != -1:
        normalized = normalized[:marker_index]

    return normalized or None


@lru_cache
def get_normalized_appwrite_endpoint() -> str:
    """Return the configured Appwrite endpoint sanitized for all CRUDs.

    Ensures the environment value works whether it is provided as the base URL
    or a ``/databases/<id>``-scoped path (including placeholders for
    ``APPWRITE_DATABASE_ID``). The result is cached to keep service factories
    consistent across the application.
    """

    settings = get_settings()
    endpoint = normalize_appwrite_endpoint(settings.appwrite_endpoint, settings.appwrite_database_id)
    if not endpoint:
        raise RuntimeError(
            "APPWRITE_ENDPOINT is not configured. Please set it in the environment."
        )
    return endpoint


__all__ = ["get_normalized_appwrite_endpoint", "normalize_appwrite_endpoint"]
