from __future__ import annotations

from functools import lru_cache

from appwrite.client import Client
from appwrite.services.databases import Databases

from src.core.config import get_settings
from src.core.appwrite_endpoint import get_normalized_appwrite_endpoint


def _require(value: str | None, env_name: str) -> str:
    if value is None or not value.strip():
        raise RuntimeError(
            f"Environment variable {env_name} is not configured. "
            "Please set it before starting the application."
        )
    return value.strip()


@lru_cache
def get_appwrite_clients() -> tuple[Client, Databases]:
    settings = get_settings()

    endpoint = get_normalized_appwrite_endpoint()
    project = _require(settings.appwrite_project_id, "APPWRITE_PROJECT_ID")
    api_key = _require(settings.appwrite_api_key, "APPWRITE_API_KEY")
    _require(settings.appwrite_database_id, "APPWRITE_DATABASE_ID")

    client = Client()
    client.set_endpoint(endpoint)
    client.set_project(project)
    client.set_key(api_key)

    databases = Databases(client)

    return client, databases
