<?php
/**
 * Monitoring Data - System health and performance monitoring
 */

try {
    $db = MongoDBConnection::getInstance()->getDatabase();
    
    // System health overview
    $system_health = [
        'database_status' => 'healthy',
        'collections_accessible' => 0,
        'total_indexes' => 0,
        'database_size' => 0,
        'storage_size' => 0,
        'recent_errors' => 0,
        'avg_response_time' => 0
    ];
    
    // Get database statistics
    try {
        $db_stats = $db->command(['dbStats' => 1])->toArray();
        if (!empty($db_stats)) {
            $stats = $db_stats[0];
            $system_health['collections_accessible'] = $stats['collections'] ?? 0;
            $system_health['total_indexes'] = $stats['indexes'] ?? 0;
            $system_health['database_size'] = $stats['dataSize'] ?? 0;
            $system_health['storage_size'] = $stats['storageSize'] ?? 0;
        }
    } catch (Exception $e) {
        error_log("Error getting database stats: " . $e->getMessage());
        $system_health['database_status'] = 'error';
    }
    
    // Collection health status
    $collection_health = [];
    $collections = ['tenants', 'apps', 'items', 'interactions', 'reco_requests', 'reco_outcomes', 'user_aliases'];
    
    foreach ($collections as $collection_name) {
        try {
            $count = $db->selectCollection($collection_name)->countDocuments([]);
            $stats = $db->command(['collStats' => $collection_name])->toArray();
            
            $collection_health[$collection_name] = [
                'status' => 'healthy',
                'document_count' => $count,
                'size' => $stats[0]['size'] ?? 0,
                'storage_size' => $stats[0]['storageSize'] ?? 0,
                'avg_obj_size' => $stats[0]['avgObjSize'] ?? 0,
                'indexes' => $stats[0]['nindexes'] ?? 0
            ];
        } catch (Exception $e) {
            error_log("Error getting stats for collection $collection_name: " . $e->getMessage());
            $collection_health[$collection_name] = [
                'status' => 'error',
                'document_count' => 0,
                'size' => 0,
                'storage_size' => 0,
                'avg_obj_size' => 0,
                'indexes' => 0,
                'error' => $e->getMessage()
            ];
        }
    }
    
    // Performance metrics
    $performance_metrics = [
        'requests_per_hour' => 0,
        'avg_request_time' => 0,
        'error_rate' => 0,
        'cache_hit_rate' => 0
    ];
    
    // Get performance data from last 24 hours
    $last_24h = new MongoDB\BSON\UTCDateTime((time() - (24 * 60 * 60)) * 1000);
    
    try {
        // Recommendation requests per hour
        $requests_count = $db->reco_requests->countDocuments([
            'req_ts' => ['$gte' => $last_24h]
        ]);
        $performance_metrics['requests_per_hour'] = round($requests_count / 24, 2);
        
        // Average response time
        $avg_pipeline = [
            ['$match' => ['req_ts' => ['$gte' => $last_24h]]],
            ['$group' => [
                '_id' => null,
                'avg_time' => ['$avg' => '$response_time_ms'],
                'total_requests' => ['$sum' => 1],
                'failed_requests' => ['$sum' => ['$cond' => [['$eq' => ['$status', 'failed']], 1, 0]]]
            ]]
        ];
        
        $avg_result = $db->reco_requests->aggregate($avg_pipeline)->toArray();
        if (!empty($avg_result)) {
            $performance_metrics['avg_request_time'] = round($avg_result[0]['avg_time'] ?? 0, 2);
            $total = $avg_result[0]['total_requests'] ?? 1;
            $failed = $avg_result[0]['failed_requests'] ?? 0;
            $performance_metrics['error_rate'] = round(($failed / $total) * 100, 2);
        }
    } catch (Exception $e) {
        error_log("Error getting performance metrics: " . $e->getMessage());
    }
    
    // Recent error logs
    $recent_errors = [];
    try {
        $error_cursor = $db->reco_requests->find(
            [
                'status' => 'failed',
                'req_ts' => ['$gte' => $last_24h]
            ],
            [
                'sort' => ['req_ts' => -1],
                'limit' => 10,
                'projection' => [
                    'tenant_id' => 1,
                    'app_id' => 1,
                    'req_ts' => 1,
                    'error_message' => 1,
                    'response_time_ms' => 1
                ]
            ]
        );
        
        foreach ($error_cursor as $error) {
            $recent_errors[] = [
                'timestamp' => $error['req_ts'],
                'tenant_id' => $error['tenant_id'],
                'app_id' => $error['app_id'] ?? '',
                'error_message' => $error['error_message'] ?? 'Unknown error',
                'response_time' => $error['response_time_ms'] ?? 0
            ];
        }
        
        $system_health['recent_errors'] = count($recent_errors);
    } catch (Exception $e) {
        error_log("Error getting recent errors: " . $e->getMessage());
    }
    
    // Resource usage trends
    $resource_trends = [];
    try {
        // Get daily usage for the last 7 days
        $seven_days_ago = new MongoDB\BSON\UTCDateTime((time() - (7 * 24 * 60 * 60)) * 1000);
        
        $trends_pipeline = [
            ['$match' => ['req_ts' => ['$gte' => $seven_days_ago]]],
            ['$group' => [
                '_id' => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$req_ts']],
                'requests' => ['$sum' => 1],
                'avg_response_time' => ['$avg' => '$response_time_ms'],
                'errors' => ['$sum' => ['$cond' => [['$eq' => ['$status', 'failed']], 1, 0]]]
            ]],
            ['$sort' => ['_id' => 1]]
        ];
        
        $trends_result = $db->reco_requests->aggregate($trends_pipeline)->toArray();
        foreach ($trends_result as $trend) {
            $resource_trends[] = [
                'date' => $trend['_id'],
                'requests' => $trend['requests'],
                'avg_response_time' => round($trend['avg_response_time'], 2),
                'errors' => $trend['errors'],
                'error_rate' => round(($trend['errors'] / $trend['requests']) * 100, 2)
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting resource trends: " . $e->getMessage());
    }
    
    // Active connections and sessions
    $active_sessions = [
        'total_sessions' => 0,
        'unique_users_24h' => 0,
        'peak_concurrent' => 0
    ];
    
    try {
        // Unique users in last 24 hours
        $unique_users_pipeline = [
            ['$match' => ['ts' => ['$gte' => $last_24h]]],
            ['$group' => ['_id' => '$user_id']],
            ['$count' => 'unique_users']
        ];
        
        $unique_result = $db->interactions->aggregate($unique_users_pipeline)->toArray();
        $active_sessions['unique_users_24h'] = $unique_result[0]['unique_users'] ?? 0;
        
        // Total interactions as proxy for sessions
        $active_sessions['total_sessions'] = $db->interactions->countDocuments([
            'ts' => ['$gte' => $last_24h]
        ]);
    } catch (Exception $e) {
        error_log("Error getting active sessions: " . $e->getMessage());
    }
    
    // Alert thresholds and warnings
    $alerts = [];
    
    // Check error rate
    if ($performance_metrics['error_rate'] > 5) {
        $alerts[] = [
            'type' => 'warning',
            'message' => 'High error rate detected: ' . $performance_metrics['error_rate'] . '%',
            'severity' => $performance_metrics['error_rate'] > 10 ? 'critical' : 'warning'
        ];
    }
    
    // Check response time
    if ($performance_metrics['avg_request_time'] > 1000) {
        $alerts[] = [
            'type' => 'warning',
            'message' => 'Slow response time: ' . $performance_metrics['avg_request_time'] . 'ms',
            'severity' => $performance_metrics['avg_request_time'] > 2000 ? 'critical' : 'warning'
        ];
    }
    
    // Check collection accessibility
    $unhealthy_collections = array_filter($collection_health, function($health) {
        return $health['status'] !== 'healthy';
    });
    
    if (!empty($unhealthy_collections)) {
        $alerts[] = [
            'type' => 'error',
            'message' => 'Collections with issues: ' . implode(', ', array_keys($unhealthy_collections)),
            'severity' => 'critical'
        ];
    }
    
    // Overall system status
    $overall_status = 'healthy';
    if (!empty($alerts)) {
        $critical_alerts = array_filter($alerts, function($alert) {
            return $alert['severity'] === 'critical';
        });
        $overall_status = !empty($critical_alerts) ? 'critical' : 'warning';
    }

} catch (Exception $e) {
    error_log("Monitoring data error: " . $e->getMessage());
    
    // Fallback data
    $system_health = [
        'database_status' => 'error',
        'collections_accessible' => 0,
        'total_indexes' => 0,
        'database_size' => 0,
        'storage_size' => 0,
        'recent_errors' => 0,
        'avg_response_time' => 0
    ];
    $collection_health = [];
    $performance_metrics = [
        'requests_per_hour' => 0,
        'avg_request_time' => 0,
        'error_rate' => 0,
        'cache_hit_rate' => 0
    ];
    $recent_errors = [];
    $resource_trends = [];
    $active_sessions = [
        'total_sessions' => 0,
        'unique_users_24h' => 0,
        'peak_concurrent' => 0
    ];
    $alerts = [[
        'type' => 'error',
        'message' => 'Failed to load monitoring data: ' . $e->getMessage(),
        'severity' => 'critical'
    ]];
    $overall_status = 'error';
    $error_message = "Failed to load monitoring data: " . $e->getMessage();
}

?>
