"""Database connection - Storage Bucket with Local fallback""" import os from config import Config # Storage mode: 'storage_bucket' or 'local' STORAGE_MODE = None _db_client = None _db_error: str = None def _init_storage_bucket(): """Try to initialize Supabase Storage Bucket DB""" global STORAGE_MODE, _db_client, _db_error supabase_url = Config.SUPABASE_URL supabase_key = Config.SUPABASE_KEY if not supabase_url or not supabase_key or supabase_key == '': _db_error = "SUPABASE credentials not set" print(f"[DB] {_db_error} - falling back to local storage") return False try: from supabase import create_client from database.storage_bucket_db import StorageBucketDB supabase_client = create_client(supabase_url, supabase_key) _db_client = StorageBucketDB(supabase_client) STORAGE_MODE = 'storage_bucket' print("[DB] ✅ Using Supabase STORAGE BUCKET (analytics-data)") return True except Exception as e: _db_error = f"Failed to init storage bucket: {str(e)}" print(f"[DB ERROR] {_db_error}") return False def _init_local(): """Initialize local file storage""" global STORAGE_MODE, _db_client, _db_error try: from database.local_storage import get_local_storage _db_client = get_local_storage() STORAGE_MODE = 'local' print("[DB] Using LOCAL FILE STORAGE (/tmp/analytics_data)") return True except Exception as e: _db_error = f"Failed to init local storage: {str(e)}" print(f"[DB ERROR] {_db_error}") return False def _init_db(): """Initialize - tries Storage Bucket first, then local""" if not _init_storage_bucket(): _init_local() # Initialize on module load _init_db() def get_db(): """Get database client""" if _db_client is None: _init_db() if _db_client is None: raise RuntimeError(f"No database: {_db_error}") return _db_client def get_db_or_none(): return _db_client def get_db_error(): return _db_error def get_storage_mode(): return STORAGE_MODE