import json import os import logging import firebase_admin from firebase_admin import credentials, firestore_async logger = logging.getLogger(__name__) def init_firebase(): """Initializes the Firebase Admin SDK singleton. Credential resolution order: 1. FIREBASE_CREDENTIALS_JSON — full service-account JSON as a string (used on HF Spaces, where no key file can be committed). 2. FIREBASE_CREDENTIALS_PATH — path to a service-account JSON file. 3. Application default credentials (Cloud Run / gcloud). """ if not firebase_admin._apps: cred_json = os.getenv("FIREBASE_CREDENTIALS_JSON", "").strip() cred_path = os.getenv("FIREBASE_CREDENTIALS_PATH", "serviceAccountKey.json") try: if cred_json: cred = credentials.Certificate(json.loads(cred_json)) firebase_admin.initialize_app(cred) logger.info("Firebase initialized from FIREBASE_CREDENTIALS_JSON env var.") elif os.path.exists(cred_path): cred = credentials.Certificate(cred_path) firebase_admin.initialize_app(cred) logger.info(f"Firebase initialized with credentials at {cred_path}") else: firebase_admin.initialize_app() logger.warning(f"Credentials not found at {cred_path}, falling back to default application credentials.") except Exception as e: logger.error(f"Failed to initialize Firebase: {e}") raise def get_async_db(): """Returns the asynchronous Firestore client.""" from google.cloud import firestore import firebase_admin import os app = firebase_admin.get_app() cred = app.credential.get_credential() db_id = os.getenv("FIRESTORE_DATABASE_ID", "default") return firestore.AsyncClient( project=app.project_id, credentials=cred, database=db_id ) def get_db(): """Returns the synchronous Firestore client.""" from google.cloud import firestore import firebase_admin import os app = firebase_admin.get_app() cred = app.credential.get_credential() db_id = os.getenv("FIRESTORE_DATABASE_ID", "default") return firestore.Client( project=app.project_id, credentials=cred, database=db_id )