File size: 9,275 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/env python3
"""

Supabase setup script for MCP AI Data Scientist.

Initializes Supabase project, applies schema, and configures real-time subscriptions.

"""

import os
import sys
import asyncio
import logging
from pathlib import Path
from typing import Optional

# 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.config import settings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def check_environment_variables():
    """Check that all required environment variables are set."""
    required_vars = [
        'SUPABASE_URL',
        'SUPABASE_ANON_KEY',
        'SUPABASE_SERVICE_ROLE_KEY'
    ]
    
    missing_vars = []
    for var in required_vars:
        if not getattr(settings, var.lower(), None):
            missing_vars.append(var)
    
    if missing_vars:
        logger.error(f"Missing required environment variables: {', '.join(missing_vars)}")
        logger.error("Please set these variables in your .env file or environment")
        return False
    
    logger.info("All required environment variables are set")
    return True


async def test_supabase_connection():
    """Test connection to Supabase."""
    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"❌ Failed to connect to Supabase: {e}")
        return False


async def apply_database_schema():
    """Apply the complete database schema to Supabase."""
    try:
        schema_file = project_root / "shared" / "sql" / "supabase_complete_schema.sql"
        
        if not schema_file.exists():
            logger.error(f"Schema file not found: {schema_file}")
            return False
        
        logger.info("⚠️  Database schema application requires manual setup")
        logger.info("Please follow these steps:")
        logger.info("1. Go to your Supabase project dashboard")
        logger.info("2. Navigate to the SQL Editor")
        logger.info(f"3. Copy and paste the contents of: {schema_file}")
        logger.info("4. Execute the SQL to create all tables and policies")
        logger.info("")
        logger.info("Alternatively, you can use the Supabase CLI:")
        logger.info("1. Install Supabase CLI: npm install -g supabase")
        logger.info("2. Login: supabase login")
        logger.info("3. Link project: supabase link --project-ref your-project-id")
        logger.info(f"4. Apply schema: supabase db push")
        logger.info("")
        logger.info("For now, we'll skip schema application and assume it's done manually.")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ Failed to prepare database schema: {e}")
        return False


async def setup_real_time_subscriptions():
    """Configure real-time subscriptions for progress tracking."""
    try:
        client = await get_supabase_client(use_service_role=True)
        
        # Enable real-time for progress_events table
        logger.info("Enabling real-time for progress_events table...")
        
        # Note: In a real Supabase setup, you would use the Supabase dashboard
        # or API to enable real-time subscriptions. This is a placeholder.
        
        logger.info("βœ… Real-time subscriptions configured")
        logger.info("Note: You may need to enable real-time for specific tables in the Supabase dashboard")
        return True
        
    except Exception as e:
        logger.error(f"❌ Failed to setup real-time subscriptions: {e}")
        return False


async def create_default_roles():
    """Create default user roles and permissions."""
    try:
        client = await get_supabase_client(use_service_role=True)
        
        logger.info("Creating default user roles...")
        
        default_roles = [
            {
                'name': 'admin',
                'description': 'Full administrative access',
                'permissions': ['admin', 'read_data', 'write_data', 'delete_data']
            },
            {
                'name': 'data_scientist',
                'description': 'Standard data scientist access',
                'permissions': ['read_data', 'write_data']
            },
            {
                'name': 'analyst',
                'description': 'Read-only analyst access',
                'permissions': ['read_data']
            },
            {
                'name': 'viewer',
                'description': 'View-only access',
                'permissions': ['read_data']
            }
        ]
        
        for role in default_roles:
            try:
                result = await asyncio.to_thread(
                    client.table('user_roles').insert(role).execute
                )
                logger.info(f"Created role: {role['name']}")
            except Exception as e:
                if "duplicate key" in str(e).lower():
                    logger.info(f"Role already exists: {role['name']}")
                else:
                    logger.warning(f"Failed to create role {role['name']}: {e}")
        
        logger.info("βœ… Default roles created")
        return True
        
    except Exception as e:
        logger.error(f"❌ Failed to create default roles: {e}")
        return False


async def verify_setup():
    """Verify that the setup was successful."""
    try:
        client = await get_supabase_client(use_service_role=True)
        
        logger.info("Verifying database setup...")
        
        # Check that key tables exist and are accessible
        tables_to_check = [
            'users',
            'analysis_sessions',
            'user_datasets',
            'hypotheses',
            'trained_models',
            'progress_events'
        ]
        
        for table in tables_to_check:
            try:
                result = await asyncio.to_thread(
                    client.table(table).select('count').limit(1).execute
                )
                logger.info(f"βœ… Table '{table}' is accessible")
            except Exception as e:
                logger.error(f"❌ Table '{table}' is not accessible: {e}")
                return False
        
        # Check that default roles exist
        result = await asyncio.to_thread(
            client.table('user_roles').select('name').execute
        )
        
        role_names = [role['name'] for role in result.data]
        expected_roles = ['admin', 'data_scientist', 'analyst', 'viewer']
        
        for role in expected_roles:
            if role in role_names:
                logger.info(f"βœ… Role '{role}' exists")
            else:
                logger.warning(f"⚠️ Role '{role}' not found")
        
        logger.info("βœ… Database setup verification completed")
        return True
        
    except Exception as e:
        logger.error(f"❌ Setup verification failed: {e}")
        return False


async def main():
    """Main setup function."""
    logger.info("πŸš€ Starting Supabase setup for MCP AI Data Scientist")
    
    # Step 1: Check environment variables
    if not await check_environment_variables():
        sys.exit(1)
    
    # Step 2: Test connection
    if not await test_supabase_connection():
        sys.exit(1)
    
    # Step 3: Apply database schema
    logger.info("πŸ“‹ Applying database schema...")
    if not await apply_database_schema():
        logger.error("Failed to apply database schema")
        sys.exit(1)
    
    # Step 4: Create default roles
    logger.info("πŸ‘₯ Creating default user roles...")
    if not await create_default_roles():
        logger.warning("Failed to create some default roles (may not be critical)")
    
    # Step 5: Setup real-time subscriptions
    logger.info("πŸ“‘ Setting up real-time subscriptions...")
    if not await setup_real_time_subscriptions():
        logger.warning("Failed to setup real-time subscriptions (may need manual configuration)")
    
    # Step 6: Verify setup
    logger.info("πŸ” Verifying setup...")
    if not await verify_setup():
        logger.error("Setup verification failed")
        sys.exit(1)
    
    logger.info("πŸŽ‰ Supabase setup completed successfully!")
    logger.info("")
    logger.info("Next steps:")
    logger.info("1. Update your .env file with the Supabase credentials")
    logger.info("2. Configure Clerk authentication integration")
    logger.info("3. Enable real-time subscriptions in the Supabase dashboard if needed")
    logger.info("4. Run the integration tests: python -m pytest tests/test_supabase_integration.py")


if __name__ == "__main__":
    asyncio.run(main())