"""
Firebase Admin SDK initialization for MCP server.
Standalone version without Django dependency.
"""
import os
import firebase_admin
from firebase_admin import credentials, firestore, auth, storage

# Global variables to hold initialized services
_db = None
_auth_client = None
_bucket = None
_initialized = False


def _initialize_firebase():
    """Initialize Firebase Admin SDK once."""
    global _db, _auth_client, _bucket, _initialized

    if _initialized:
        return

    # Initialize Firebase Admin SDK once
    if not firebase_admin._apps:
        try:
            # Try to load credentials from environment variable or default path
            cred_path = os.getenv('SERVICE_ACCOUNT_KEY_PATH', 'serviceAccountKey.json')
            if os.path.exists(cred_path):
                cred = credentials.Certificate(cred_path)
                firebase_admin.initialize_app(cred)
            else:
                # Initialize with minimal config for testing (will fail on actual Firebase calls)
                # This allows the MCP server to start without valid credentials
                print("Warning: No Firebase credentials found. MCP server will start but Firebase operations will fail.", file=sys.stderr)
                try:
                    firebase_admin.initialize_app(credentials.ApplicationDefault())
                except:
                    pass
        except Exception as e:
            print(f"Warning: Failed to initialize Firebase Admin SDK: {e}", file=sys.stderr)
            print("MCP server will start but Firebase operations will fail without valid credentials.", file=sys.stderr)
            # Initialize with minimal config to allow server to start
            try:
                firebase_admin.initialize_app(credentials.ApplicationDefault())
            except:
                pass

    # Initialize Firestore
    try:
        _db = firestore.client()
    except Exception as e:
        print(f"Warning: Failed to initialize Firestore: {e}", file=sys.stderr)

    # Initialize Auth
    try:
        _auth_client = auth
    except Exception as e:
        print(f"Warning: Failed to initialize Auth: {e}", file=sys.stderr)

    # Initialize Storage
    storage_bucket = os.getenv('FIREBASE_STORAGE_BUCKET', '')
    if storage_bucket:
        try:
            _bucket = storage.bucket(storage_bucket)
        except Exception as e:
            print(f"Warning: Failed to initialize Storage bucket: {e}", file=sys.stderr)
            _bucket = None

    _initialized = True


def get_db():
    """Get Firestore database client."""
    if not _initialized:
        _initialize_firebase()
    return _db


def get_auth():
    """Get Firebase Auth client."""
    if not _initialized:
        _initialize_firebase()
    return _auth_client


def get_bucket():
    """Get Firebase Storage bucket."""
    if not _initialized:
        _initialize_firebase()
    return _bucket