/** * Firebase Service - Handle data persistence and authentication */ import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js'; import { getFirestore, collection, addDoc, serverTimestamp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js'; import { getAuth, signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js'; // Firebase configuration const firebaseConfig = { apiKey: "AIzaSyAYbKEaWT99sDO7bUC76LcXKDRK3BBMZ00", authDomain: "embryo-one.firebaseapp.com", projectId: "embryo-one", storageBucket: "embryo-one.firebasestorage.app", messagingSenderId: "23510355257", appId: "1:23510355257:web:0ae7edce822704820f6ce8", measurementId: "G-140V7Z1GRK" }; // Initialize Firebase let app; let db; let auth; try { app = initializeApp(firebaseConfig); db = getFirestore(app); auth = getAuth(app); console.log('Firebase initialized successfully'); } catch (error) { console.error('Firebase initialization error:', error); } /** * Save embryo grading results to Firebase * @param {Object} resultData - The grading result data * @returns {Promise} - Document ID */ export async function saveGradingResults(resultData) { try { const docRef = await addDoc(collection(db, 'embryo_gradings'), { ...resultData, createdAt: serverTimestamp() }); console.log('Results saved with ID:', docRef.id); return docRef.id; } catch (error) { console.error('Error saving results:', error); throw error; } } /** * Prepare embryo data for saving * @param {Array} embryos - Array of embryo objects * @param {string} mainImageUrl - URL of the main uploaded image * @param {Array} results - Array of evaluation results * @param {Object} remarks - Object mapping index to remarks * @returns {Object} - Formatted data for Firebase */ export function prepareEmbryoData(embryos, mainImageUrl, results = [], remarks = {}) { console.log('Preparing embryo data for Firebase:'); console.log('- Embryos count:', embryos.length); console.log('- Results count:', results.length); console.log('- Remarks:', remarks); return { mainImage: mainImageUrl, embryos: embryos.map((embryo, index) => { // Get result for this embryo const resultData = results[index]; const result = resultData?.result; const embryoData = { embryoNumber: index + 1, croppedImage: embryo.imageData, predictedGrade: result?.grade || embryo.grade || 'Unknown', actualGrade: embryo.actualGrade || '', quality: result?.quality || embryo.quality || 'Unknown', confidence: result?.confidence || embryo.confidence || 0, poorGoodConfidence: result?.poorGoodConfidence || 0, remarks: remarks[index] || embryo.remarks || '', isManual: embryo.isManual || false, detectionConfidence: embryo.confidence || 0 }; console.log(`Embryo ${index + 1} data:`, { grade: embryoData.predictedGrade, quality: embryoData.quality, remarks: embryoData.remarks }); return embryoData; }), totalEmbryos: embryos.length, timestamp: new Date().toISOString() }; } /** * Check if Firebase is initialized * @returns {boolean} */ export function isFirebaseReady() { return db !== null && db !== undefined && auth !== null && auth !== undefined; } /** * Authentication Functions */ /** * Sign in with email and password * @param {string} email - User email * @param {string} password - User password * @returns {Promise} - User credential */ export async function signIn(email, password) { try { const userCredential = await signInWithEmailAndPassword(auth, email, password); console.log('User signed in:', userCredential.user.email); return userCredential; } catch (error) { console.error('Sign in error:', error); throw error; } } /** * Sign in with Google * @returns {Promise} - User credential */ export async function signInWithGoogle() { try { const provider = new GoogleAuthProvider(); provider.setCustomParameters({ prompt: 'select_account' }); const userCredential = await signInWithPopup(auth, provider); console.log('User signed in with Google:', userCredential.user.email); return userCredential; } catch (error) { console.error('Google sign in error:', error); throw error; } } /** * Sign out current user * @returns {Promise} */ export async function signOutUser() { try { await signOut(auth); console.log('User signed out'); } catch (error) { console.error('Sign out error:', error); throw error; } } /** * Get current user * @returns {Object|null} - Current user or null */ export function getCurrentUser() { return auth?.currentUser || null; } /** * Listen to authentication state changes * @param {Function} callback - Callback function to execute on auth state change * @returns {Function} - Unsubscribe function */ export function onAuthChange(callback) { if (!auth) { console.error('Auth not initialized'); return () => {}; } return onAuthStateChanged(auth, callback); }