import admin from 'firebase-admin';

// Initialize Firebase Admin SDK
if (!admin.apps.length) {
  try {
    // Check if we're running in Firebase Functions environment
    const isCloudFunction = process.env['FUNCTION_TARGET'] || process.env['FUNCTIONS_EMULATOR'];
    
    if (isCloudFunction) {
      // In Firebase Functions, use default initialization
      admin.initializeApp({
        projectId: process.env['GCLOUD_PROJECT'] || 'cim-summarizer',
      });
      console.log('Firebase Admin SDK initialized for Cloud Functions');
    } else {
      // For local development, try to use service account key if available
      try {
        const serviceAccount = require('../../serviceAccountKey.json');
        admin.initializeApp({
          credential: admin.credential.cert(serviceAccount),
          projectId: 'cim-summarizer',
        });
        console.log('Firebase Admin SDK initialized with service account');
      } catch (serviceAccountError) {
        // Fallback to default initialization
        admin.initializeApp({
          projectId: 'cim-summarizer',
        });
        console.log('Firebase Admin SDK initialized with default credentials');
      }
    }
    
    console.log('Firebase apps count:', admin.apps.length);
    console.log('Project ID:', admin.app().options.projectId);
  } catch (error) {
    console.error('Failed to initialize Firebase Admin SDK:', error);
    
    // Final fallback: try with minimal config
    try {
      admin.initializeApp();
      console.log('Firebase Admin SDK initialized with minimal fallback');
    } catch (fallbackError) {
      console.error('All Firebase initialization attempts failed:', fallbackError);
      // Don't throw here to prevent the entire app from crashing
    }
  }
}

export default admin; 