File size: 7,535 Bytes
611e2c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d74c0dc
 
 
 
611e2c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d74c0dc
611e2c1
 
 
 
 
d74c0dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611e2c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Verification script to ensure Supabase is configured and will be used for all future data.
Run this after migration to confirm everything is set up correctly.
"""

import os
import sys
from pathlib import Path
from dotenv import load_dotenv

# Add backend to path
backend_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(backend_dir))

load_dotenv()

from backend.api.storage.rules_store import RulesStore
from backend.api.storage.analytics_store import AnalyticsStore

def main():
    print("=" * 70)
    print("Supabase Configuration Verification")
    print("=" * 70)
    print()
    
    # Check environment variables
    print("1. Checking Environment Variables:")
    postgres_url = os.getenv("POSTGRESQL_URL")
    supabase_url = os.getenv("SUPABASE_URL")
    supabase_key = os.getenv("SUPABASE_SERVICE_KEY")
    
    has_postgres = bool(postgres_url)
    has_supabase_api = bool(supabase_url and supabase_key)
    
    if has_postgres:
        masked = postgres_url[:30] + "..." + postgres_url[-20:] if len(postgres_url) > 50 else postgres_url
        print(f"   βœ… POSTGRESQL_URL is set: {masked}")
    else:
        print("   ❌ POSTGRESQL_URL is not set")
    
    if supabase_url:
        print(f"   βœ… SUPABASE_URL is set: {supabase_url[:50]}...")
    else:
        print("   ❌ SUPABASE_URL is not set")
    
    if supabase_key:
        if len(supabase_key) > 100:
            print(f"   βœ… SUPABASE_SERVICE_KEY is set: {supabase_key[:20]}... ({len(supabase_key)} chars)")
        else:
            print(f"   ❌ SUPABASE_SERVICE_KEY seems incomplete ({len(supabase_key)} chars, expected 200+)")
            print("   ⚠️  This looks like an 'anon' key, not a 'service_role' key!")
            print("   πŸ’‘ You need the SERVICE_ROLE key (not anon key) for backend operations")
            print("   πŸ’‘ Get it from: Supabase Dashboard β†’ Settings β†’ API β†’ service_role key")
    else:
        print("   ❌ SUPABASE_SERVICE_KEY is not set")
    
    print()
    
    # Check RulesStore
    print("2. Checking RulesStore Configuration:")
    try:
        rules_store = RulesStore()
        if rules_store.use_supabase:
            print("   βœ… RulesStore is using Supabase")
            print(f"   πŸ“¦ Backend: Supabase (REST API)")
        else:
            print("   ❌ RulesStore is using SQLite (not Supabase)")
            print("   ⚠️  Future rules will be saved to SQLite, not Supabase!")
            print()
            print("   To fix:")
            print("   - Set SUPABASE_URL and SUPABASE_SERVICE_KEY in .env")
    except Exception as e:
        print(f"   ❌ Error initializing RulesStore: {e}")
    
    print()
    
    # Check AnalyticsStore
    print("3. Checking AnalyticsStore Configuration:")
    analytics_store = None
    try:
        analytics_store = AnalyticsStore()
        if analytics_store.use_supabase:
            print("   βœ… AnalyticsStore is using Supabase")
            print(f"   πŸ“¦ Backend: Supabase (REST API)")
            
            # Test table verification
            if analytics_store._tables_verified:
                print("   βœ… Analytics tables verified and accessible")
            else:
                print("   ⚠️  Analytics tables not verified")
                print("   ⚠️  This may cause inserts to fail!")
                print("   πŸ’‘ Solution: Run supabase_analytics_tables.sql in Supabase SQL Editor")
            
            # Test actual insert
            print()
            print("   πŸ§ͺ Testing actual insert to Supabase...")
            try:
                test_tenant = "test_verification"
                analytics_store.log_tool_usage(
                    tenant_id=test_tenant,
                    tool_name="verification_test",
                    latency_ms=1,
                    success=True
                )
                print("   βœ… Test insert successful! Data is being saved to Supabase.")
            except Exception as insert_error:
                error_str = str(insert_error)
                print(f"   ❌ Test insert failed: {insert_error}")
                print("   πŸ’‘ This indicates:")
                
                # Check for specific error types
                if "Invalid API key" in error_str or "401" in error_str:
                    print("      ❌ INVALID API KEY - This is the main issue!")
                    print("      πŸ’‘ Your SUPABASE_SERVICE_KEY is incorrect or incomplete")
                    print("      πŸ’‘ Get the correct key from: Supabase Dashboard β†’ Settings β†’ API")
                    print("      πŸ’‘ Make sure you're using the 'service_role' key (not 'anon' key)")
                    print("      πŸ’‘ The service_role key should be 200+ characters long")
                elif "does not exist" in error_str.lower() or "relation" in error_str.lower():
                    print("      - Tables may not exist (run supabase_analytics_tables.sql)")
                elif "RLS" in error_str or "policy" in error_str.lower():
                    print("      - RLS policies may be blocking inserts")
                else:
                    print("      - Schema mismatch between code and database")
                    print("      - Check Supabase logs for more details")
        else:
            print("   ❌ AnalyticsStore is using SQLite (not Supabase)")
            print("   ⚠️  Future analytics will be saved to SQLite, not Supabase!")
            print()
            print("   To fix:")
            if has_postgres:
                print("   - POSTGRESQL_URL is set, but AnalyticsStore needs SUPABASE_URL + SUPABASE_SERVICE_KEY")
            else:
                print("   - Set SUPABASE_URL and SUPABASE_SERVICE_KEY in .env")
    except Exception as e:
        print(f"   ❌ Error initializing AnalyticsStore: {e}")
    
    print()
    
    # Summary
    print("4. Summary:")
    rules_ok = rules_store.use_supabase if 'rules_store' in locals() else False
    analytics_ok = analytics_store.use_supabase if 'analytics_store' in locals() else False
    
    if rules_ok and analytics_ok:
        print("   βœ… All systems configured to use Supabase!")
        print("   βœ… Future data will be saved to Supabase")
        print()
        print("   πŸ’‘ Next steps:")
        print("   1. Restart your FastAPI/MCP services to apply changes")
        print("   2. Test by adding a rule or generating analytics")
        print("   3. Verify data appears in Supabase Dashboard β†’ Table Editor")
    elif rules_ok or analytics_ok:
        print("   ⚠️  Partial configuration:")
        if rules_ok:
            print("   βœ… Rules will use Supabase")
        else:
            print("   ❌ Rules will use SQLite")
        if analytics_ok:
            print("   βœ… Analytics will use Supabase")
        else:
            print("   ❌ Analytics will use SQLite")
        print()
        print("   To fully migrate to Supabase:")
        print("   - Ensure SUPABASE_URL and SUPABASE_SERVICE_KEY are set in .env")
        print("   - Restart your services")
    else:
        print("   ❌ Not configured for Supabase")
        print("   ⚠️  All data will be saved to SQLite")
        print()
        print("   To migrate to Supabase:")
        print("   1. Set SUPABASE_URL and SUPABASE_SERVICE_KEY in .env")
        print("   2. Restart your services")
        print("   3. Run this verification again")
    
    print()
    print("=" * 70)

if __name__ == "__main__":
    main()