# firebase/firebase_config.py import firebase_admin from firebase_admin import credentials, firestore import os import json FALLBACK_LOG_PATH = "data/logs.json" def init_firebase(): try: if not firebase_admin._apps: cred_path = "firebase_credentials.json" if not os.path.exists(cred_path): raise FileNotFoundError("Firebase credentials file not found.") cred = credentials.Certificate(cred_path) firebase_admin.initialize_app(cred) return firestore.client() except Exception as e: print(f"[Firebase ERROR] {e}") return None def log_message_to_firestore(message_dict): db = init_firebase() if db: try: chat_ref = db.collection("conversations").document("bot_talk_log") chat_ref.set({"messages": firestore.ArrayUnion([message_dict])}, merge=True) return except Exception as e: print(f"[Firestore ERROR] {e}") # Fallback if Firebase not available log_to_local_file(message_dict) def log_to_local_file(message_dict): os.makedirs("data", exist_ok=True) # Read existing logs if os.path.exists(FALLBACK_LOG_PATH): with open(FALLBACK_LOG_PATH, "r") as f: try: logs = json.load(f) except json.JSONDecodeError: logs = [] else: logs = [] logs.append(message_dict) with open(FALLBACK_LOG_PATH, "w") as f: json.dump(logs, f, indent=2) print("[Local LOG] Message saved to fallback log.")