from __future__ import annotations

import json
import os
from functools import lru_cache
from typing import Optional

import firebase_admin
from firebase_admin import credentials, firestore

from app.core.config import get_settings


def _load_credentials() -> Optional[credentials.Base]:
    settings = get_settings()
    cred_path = settings.firestore.credentials_path

    if cred_path and os.path.exists(cred_path):
        return credentials.Certificate(cred_path)

    env_key = os.environ.get("GCP_SA_KEY")
    if env_key:
        try:
            return credentials.Certificate(json.loads(env_key))
        except json.JSONDecodeError:
            pass

    return None


@lru_cache
def get_firestore_client() -> firestore.Client:
    if not firebase_admin._apps:
        cred = _load_credentials()
        if cred:
            firebase_admin.initialize_app(cred)
        else:
            firebase_admin.initialize_app()

    settings = get_settings()
    if settings.firestore.emulator_host:
        os.environ.setdefault("FIRESTORE_EMULATOR_HOST", settings.firestore.emulator_host)

    return firestore.client()
