#!/usr/bin/env python3 """ Quick validation script for Supabase setup. Tests basic functionality without running full integration tests. """ import os import sys import asyncio import logging from pathlib import Path from uuid import uuid4 # Add project root to path project_root = Path(__file__).parent.parent sys.path.insert(0, str(project_root)) from shared.supabase_config import supabase_config, get_supabase_client from shared.database import SupabaseManager from shared.models import UserContext from shared.config import settings logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def validate_environment(): """Validate environment configuration.""" logger.info("๐Ÿ” Validating environment configuration...") required_vars = ['supabase_url', 'supabase_anon_key', 'supabase_service_role_key'] missing_vars = [] for var in required_vars: if not getattr(settings, var, None): missing_vars.append(var.upper()) if missing_vars: logger.error(f"โŒ Missing environment variables: {', '.join(missing_vars)}") return False logger.info("โœ… Environment configuration is valid") return True async def validate_connection(): """Validate Supabase connection.""" logger.info("๐Ÿ”— Testing Supabase connection...") try: await supabase_config.initialize() health_status = await supabase_config.health_check() if health_status: logger.info("โœ… Supabase connection successful") return True else: logger.error("โŒ Supabase health check failed") return False except Exception as e: logger.error(f"โŒ Connection failed: {e}") return False async def validate_database_schema(): """Validate that required tables exist.""" logger.info("๐Ÿ“‹ Validating database schema...") try: client = await get_supabase_client(use_service_role=True) required_tables = [ 'users', 'analysis_sessions', 'user_datasets', 'hypotheses', 'hypothesis_results', 'trained_models', 'progress_events', 'business_recommendations' ] missing_tables = [] for table in required_tables: try: result = await asyncio.to_thread( client.table(table).select('count').limit(1).execute ) logger.info(f"โœ… Table '{table}' exists and is accessible") except Exception as e: logger.error(f"โŒ Table '{table}' not accessible: {e}") missing_tables.append(table) if missing_tables: logger.error(f"โŒ Missing or inaccessible tables: {', '.join(missing_tables)}") return False logger.info("โœ… Database schema validation successful") return True except Exception as e: logger.error(f"โŒ Schema validation failed: {e}") return False async def validate_user_operations(): """Validate basic user operations.""" logger.info("๐Ÿ‘ค Testing user operations...") try: db_manager = SupabaseManager() await db_manager.initialize() # Create test user context test_user = UserContext( user_id=f"test_validation_{uuid4().hex[:8]}", email="validation@test.com", permissions=["read_data", "write_data"] ) # Test user creation created = await db_manager.create_user_if_not_exists(test_user) if created: logger.info("โœ… User creation successful") else: logger.info("โœ… User already exists (expected)") # Test session creation session_data = { 'name': 'Validation Test Session', 'business_context': 'Testing basic operations' } session_id = await db_manager.create_analysis_session(test_user, session_data) logger.info(f"โœ… Analysis session created: {session_id}") # Test session retrieval session = await db_manager.get_analysis_session(test_user, session_id) if session and session['name'] == 'Validation Test Session': logger.info("โœ… Session retrieval successful") else: logger.error("โŒ Session retrieval failed") return False # Test session update updates = {'status': 'running', 'progress_percentage': 50} success = await db_manager.update_analysis_session(test_user, session_id, updates) if success: logger.info("โœ… Session update successful") else: logger.error("โŒ Session update failed") return False logger.info("โœ… User operations validation successful") return True except Exception as e: logger.error(f"โŒ User operations validation failed: {e}") return False async def validate_real_time(): """Validate real-time functionality.""" logger.info("๐Ÿ“ก Testing real-time functionality...") try: from shared.supabase_config import broadcast_progress test_user_id = f"test_realtime_{uuid4().hex[:8]}" test_session_id = str(uuid4()) # Broadcast a test progress event await broadcast_progress( user_id=test_user_id, session_id=test_session_id, event_type="validation_test", stage="testing", progress_percentage=100, message="Real-time validation test", details={"test": True} ) # Verify the event was stored client = await get_supabase_client(use_service_role=True) result = await asyncio.to_thread( client.table('progress_events') .select('*') .eq('session_id', test_session_id) .eq('user_id', test_user_id) .execute ) if result.data and len(result.data) > 0: event = result.data[0] if (event['event_type'] == 'validation_test' and event['stage'] == 'testing' and event['progress_percentage'] == 100): logger.info("โœ… Real-time event broadcasting successful") return True else: logger.error("โŒ Real-time event data mismatch") return False else: logger.error("โŒ Real-time event not found in database") return False except Exception as e: logger.error(f"โŒ Real-time validation failed: {e}") return False async def validate_rls_policies(): """Validate Row Level Security policies.""" logger.info("๐Ÿ”’ Testing Row Level Security policies...") try: # Note: Full RLS testing requires authenticated clients # This is a basic test to ensure RLS is enabled client = await get_supabase_client(use_service_role=True) # Check that RLS is enabled on key tables rls_tables = ['users', 'analysis_sessions', 'user_datasets', 'hypotheses'] for table in rls_tables: try: # This query should work with service role result = await asyncio.to_thread( client.table(table).select('count').limit(1).execute ) logger.info(f"โœ… RLS table '{table}' accessible with service role") except Exception as e: logger.error(f"โŒ RLS table '{table}' not accessible: {e}") return False logger.info("โœ… RLS policies validation successful") logger.info("โ„น๏ธ Note: Full RLS testing requires authenticated user tokens") return True except Exception as e: logger.error(f"โŒ RLS validation failed: {e}") return False async def cleanup_test_data(): """Clean up test data created during validation.""" logger.info("๐Ÿงน Cleaning up test data...") try: client = await get_supabase_client(use_service_role=True) # Clean up test users await asyncio.to_thread( client.table('users') .delete() .like('clerk_user_id', 'test_validation_%') .execute ) # Clean up test progress events await asyncio.to_thread( client.table('progress_events') .delete() .like('user_id', 'test_realtime_%') .execute ) logger.info("โœ… Test data cleanup completed") except Exception as e: logger.warning(f"โš ๏ธ Test data cleanup failed (non-critical): {e}") async def main(): """Main validation function.""" logger.info("๐Ÿš€ Starting Supabase setup validation") validation_steps = [ ("Environment Configuration", validate_environment), ("Database Connection", validate_connection), ("Database Schema", validate_database_schema), ("User Operations", validate_user_operations), ("Real-time Functionality", validate_real_time), ("Row Level Security", validate_rls_policies), ] passed_steps = 0 total_steps = len(validation_steps) for step_name, step_function in validation_steps: logger.info(f"\n๐Ÿ“‹ Step: {step_name}") try: if await step_function(): passed_steps += 1 else: logger.error(f"โŒ Step failed: {step_name}") except Exception as e: logger.error(f"โŒ Step error: {step_name} - {e}") # Cleanup test data await cleanup_test_data() # Summary logger.info(f"\n๐Ÿ“Š Validation Summary:") logger.info(f"Passed: {passed_steps}/{total_steps} steps") if passed_steps == total_steps: logger.info("๐ŸŽ‰ All validation steps passed! Supabase setup is working correctly.") logger.info("\nNext steps:") logger.info("1. Run full integration tests: python -m pytest tests/test_supabase_integration.py") logger.info("2. Configure Clerk authentication integration") logger.info("3. Test the complete MCP pipeline") return True else: logger.error(f"โŒ {total_steps - passed_steps} validation steps failed.") logger.error("Please check the errors above and fix the issues before proceeding.") return False if __name__ == "__main__": success = asyncio.run(main()) sys.exit(0 if success else 1)