File size: 6,654 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
#!/usr/bin/env python3
"""

Simple Supabase setup validation script.

Checks configuration without requiring actual database connection.

"""

import os
import sys
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from shared.config import settings

def check_environment_variables():
    """Check that all required environment variables are set."""
    print("πŸ” Checking environment variables...")
    
    required_vars = [
        ('SUPABASE_URL', settings.supabase_url),
        ('SUPABASE_ANON_KEY', settings.supabase_anon_key),
        ('SUPABASE_SERVICE_ROLE_KEY', settings.supabase_service_role_key)
    ]
    
    all_set = True
    
    for var_name, var_value in required_vars:
        if not var_value or var_value in ['your-project-id', 'your-anon-key-here', 'your-service-role-key-here', '**** **** **** ****']:
            print(f"❌ {var_name} is not set or contains placeholder value")
            all_set = False
        else:
            print(f"βœ… {var_name} is configured")
    
    return all_set


def validate_supabase_url():
    """Validate Supabase URL format."""
    print("\nπŸ”— Validating Supabase URL format...")
    
    url = settings.supabase_url
    if not url:
        print("❌ SUPABASE_URL is not set")
        return False
    
    if not url.startswith('https://') or not url.endswith('.supabase.co'):
        print(f"❌ Invalid Supabase URL format: {url}")
        print("   Expected format: https://your-project-id.supabase.co")
        return False
    
    print(f"βœ… Supabase URL format is valid: {url}")
    return True


def validate_api_keys():
    """Validate API key formats."""
    print("\nπŸ”‘ Validating API key formats...")
    
    anon_key = settings.supabase_anon_key
    service_key = settings.supabase_service_role_key
    
    valid = True
    
    # Check anon key
    if not anon_key or len(anon_key) < 100:
        print("❌ SUPABASE_ANON_KEY appears to be invalid (too short)")
        valid = False
    elif not anon_key.startswith('eyJ'):
        print("❌ SUPABASE_ANON_KEY doesn't appear to be a JWT token")
        valid = False
    else:
        print("βœ… SUPABASE_ANON_KEY format looks valid")
    
    # Check service role key
    if not service_key or len(service_key) < 100:
        print("❌ SUPABASE_SERVICE_ROLE_KEY appears to be invalid (too short)")
        valid = False
    elif not service_key.startswith('eyJ'):
        print("❌ SUPABASE_SERVICE_ROLE_KEY doesn't appear to be a JWT token")
        valid = False
    else:
        print("βœ… SUPABASE_SERVICE_ROLE_KEY format looks valid")
    
    return valid


def check_schema_file():
    """Check that the schema file exists."""
    print("\nπŸ“‹ Checking database schema file...")
    
    schema_file = project_root / "shared" / "sql" / "supabase_complete_schema.sql"
    
    if not schema_file.exists():
        print(f"❌ Schema file not found: {schema_file}")
        return False
    
    # Check file size
    file_size = schema_file.stat().st_size
    if file_size < 1000:  # Should be much larger
        print(f"❌ Schema file seems too small: {file_size} bytes")
        return False
    
    print(f"βœ… Schema file found: {schema_file} ({file_size} bytes)")
    return True


def print_setup_instructions():
    """Print setup instructions."""
    print("\nπŸ“‹ Supabase Setup Instructions:")
    print("=" * 50)
    
    print("\n1. Create Supabase Project:")
    print("   - Go to https://supabase.com")
    print("   - Click 'New Project'")
    print("   - Choose organization and project name")
    print("   - Set database password")
    print("   - Wait for project creation (2-3 minutes)")
    
    print("\n2. Get API Credentials:")
    print("   - Go to Project Settings > API")
    print("   - Copy Project URL")
    print("   - Copy 'anon public' key")
    print("   - Copy 'service_role secret' key")
    
    print("\n3. Update Environment Variables:")
    print("   - Edit your .env file")
    print("   - Replace placeholder values with actual credentials")
    print("   - Save the file")
    
    print("\n4. Apply Database Schema:")
    print("   - Go to your Supabase project dashboard")
    print("   - Navigate to SQL Editor")
    print("   - Copy contents of shared/sql/supabase_complete_schema.sql")
    print("   - Paste and execute in SQL Editor")
    
    print("\n5. Configure Authentication (Optional):")
    print("   - Go to Authentication > Providers")
    print("   - Configure Clerk integration if needed")
    
    print("\n6. Enable Real-time (Optional):")
    print("   - Go to Database > Replication")
    print("   - Enable real-time for progress_events table")
    print("   - Enable real-time for analysis_sessions table")
    
    print("\n7. Test Setup:")
    print("   - Run: python scripts/validate_supabase_setup.py")
    print("   - Run: python -m pytest tests/test_supabase_integration.py")


def main():
    """Main validation function."""
    print("πŸš€ Supabase Setup Validation")
    print("=" * 40)
    
    # Check environment variables
    env_ok = check_environment_variables()
    
    # Validate URL format
    url_ok = validate_supabase_url()
    
    # Validate API keys
    keys_ok = validate_api_keys()
    
    # Check schema file
    schema_ok = check_schema_file()
    
    # Summary
    print("\nπŸ“Š Validation Summary:")
    print("=" * 30)
    
    checks = [
        ("Environment Variables", env_ok),
        ("Supabase URL Format", url_ok),
        ("API Key Formats", keys_ok),
        ("Schema File", schema_ok)
    ]
    
    passed = sum(1 for _, ok in checks if ok)
    total = len(checks)
    
    for check_name, ok in checks:
        status = "βœ… PASS" if ok else "❌ FAIL"
        print(f"{check_name}: {status}")
    
    print(f"\nOverall: {passed}/{total} checks passed")
    
    if passed == total:
        print("\nπŸŽ‰ Configuration looks good!")
        print("Next steps:")
        print("1. Apply the database schema in Supabase dashboard")
        print("2. Test connection with: python scripts/validate_supabase_setup.py")
    else:
        print(f"\n⚠️  {total - passed} issues found.")
        print("Please fix the issues above before proceeding.")
        print_setup_instructions()
    
    return passed == total


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)