File size: 4,031 Bytes
8a682b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Database utilities for the AI Agent system
Provides vector store access and database connection management
"""

import os
import logging
from typing import Optional, Any
from supabase import create_client, Client

logger = logging.getLogger(__name__)

# Global client instance
_supabase_client: Optional[Client] = None
_vector_store: Optional[Any] = None

def get_supabase_client() -> Client:
    """Get or create Supabase client"""
    global _supabase_client
    
    if _supabase_client is None:
        url = os.getenv("SUPABASE_URL")
        key = os.getenv("SUPABASE_KEY")
        
        if not url or not key:
            raise ValueError("SUPABASE_URL and SUPABASE_KEY environment variables are required")
        
        _supabase_client = create_client(url, key)
        logger.info("Supabase client initialized")
    
    return _supabase_client

def get_vector_store():
    """Get vector store instance"""
    global _vector_store
    
    if _vector_store is None:
        try:
            # Try to get from enhanced database
            from .database_enhanced import initialize_supabase_enhanced
            import asyncio
            
            # Initialize enhanced vector store
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                components = loop.run_until_complete(initialize_supabase_enhanced())
                _vector_store = components.get('vector_store')
            finally:
                loop.close()
                
        except Exception as e:
            logger.warning(f"Could not initialize enhanced vector store: {e}")
            _vector_store = None
    
    return _vector_store

class SupabaseLogHandler(logging.Handler):
    """Custom log handler for Supabase"""
    
    def __init__(self, client: Client):
        super().__init__()
        self.client = client
    
    def emit(self, record):
        try:
            # Create log entry
            log_entry = {
                'level': record.levelname,
                'message': record.getMessage(),
                'module': record.module,
                'function': record.funcName,
                'line': record.lineno,
                'timestamp': record.created
            }
            
            # Insert into logs table
            self.client.table('logs').insert(log_entry).execute()
            
        except Exception as e:
            # Don't let logging errors crash the application
            print(f"Log handler error: {e}")
    
    def log_interaction(self, session_id: str, user_message: str, assistant_response: str):
        """Log user interaction"""
        try:
            interaction = {
                'session_id': session_id,
                'user_message': user_message,
                'assistant_response': assistant_response,
                'timestamp': 'now()'
            }
            
            self.client.table('interactions').insert(interaction).execute()
            
        except Exception as e:
            logger.error(f"Failed to log interaction: {e}")

def create_tables():
    """Create necessary database tables"""
    try:
        client = get_supabase_client()
        
        # Create logs table
        client.rpc('create_logs_table').execute()
        
        # Create interactions table
        client.rpc('create_interactions_table').execute()
        
        logger.info("Database tables created successfully")
        
    except Exception as e:
        logger.error(f"Failed to create tables: {e}")

def health_check() -> dict:
    """Check database health"""
    try:
        client = get_supabase_client()
        
        # Test connection
        response = client.table('logs').select('count').limit(1).execute()
        
        return {
            'status': 'healthy',
            'connection': 'ok',
            'tables': 'accessible'
        }
        
    except Exception as e:
        return {
            'status': 'unhealthy',
            'error': str(e)
        }