File size: 2,214 Bytes
3d93756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter
import os
import json
from datetime import datetime
from supabase import create_client, Client

router = APIRouter()

@router.get("/test-supabase", summary="Debug Supabase Connection")
async def test_supabase():
    """
    Debug endpoint to test Supabase connection and insertion.
    WARNING: Public endpoint for debugging only. Remove after use.
    """
    results = {
        "timestamp": datetime.now().isoformat(),
        "env_vars": {},
        "connection": "pending",
        "insert": "pending",
        "error": None
    }

    # 1. Check Env Vars
    url = os.getenv("SUPABASE_URL")
    key = os.getenv("SUPABASE_ANON_KEY") or os.getenv("SUPABASE_SERVICE_ROLE_KEY")
    enable_metrics = os.getenv("ENABLE_METRICS_LOGGING", "false").lower() == "true"

    results["env_vars"] = {
        "SUPABASE_URL_SET": bool(url),
        "SUPABASE_KEY_SET": bool(key),
        "ENABLE_METRICS_LOGGING": enable_metrics,
        "ENABLE_METRICS_LOGGING_RAW": os.getenv("ENABLE_METRICS_LOGGING")
    }

    if not url or not key:
        results["connection"] = "failed"
        results["error"] = "Missing SUPABASE_URL or SUPABASE_KEY env vars"
        return results

    # 2. Connect
    try:
        supabase: Client = create_client(url, key)
        results["connection"] = "success"
    except Exception as e:
        results["connection"] = "failed"
        results["error"] = f"Client init failed: {str(e)}"
        return results

    # 3. Test Insert
    payload = {
        "question": "DEBUG_ENDPOINT_PROBE",
        "answer": "This is a test row from /api/test-supabase",
        "provenance": "debug_endpoint",
        "user_id": "debug_user"
    }
    
    try:
        response = supabase.table("metrics_chat_answers").insert(payload).execute()
        results["insert"] = "success"
        results["data"] = response.data
    except Exception as e:
        results["insert"] = "failed"
        results["error"] = f"Insert failed: {str(e)}"
        # Add hint about RLS
        if "policy" in str(e).lower() or "permission" in str(e).lower():
            results["hint"] = "Check Row Level Security (RLS) policies for 'metrics_chat_answers' table."

    return results