import firebase_admin
from firebase_admin import credentials, firestore, storage
from config import settings

db = None
bucket = None
firebase_initialized = False


def init_firebase():
    """Initialize Firebase Admin SDK. Call once at app startup."""
    global db, bucket, firebase_initialized
    try:
        cred = credentials.Certificate(settings.firebase_service_account_path)
        firebase_admin.initialize_app(cred, {
            "storageBucket": settings.firebase_storage_bucket,
        })
        db = firestore.client()
        bucket = storage.bucket()
        firebase_initialized = True
    except Exception as e:
        print(f"[WARNING] Firebase init failed: {e}")
        firebase_initialized = False


def get_db():
    """Return the Firestore client. None if Firebase is not initialized."""
    return db


def get_bucket():
    """Return the Firebase Storage bucket. None if Firebase is not initialized."""
    return bucket
