<?php
/**
 * API to check diversity rules compliance for a participant's scores
 * Usage: GET /api/check_diversity_rules.php?ep_id=123&judge_id=456&event_id=789
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../includes/db.php';

try {
    // Get parameters
    $ep_id = $_GET['ep_id'] ?? '';
    $judge_id = $_GET['judge_id'] ?? '';
    $event_id = $_GET['event_id'] ?? '';
    $heat_number = $_GET['heat_number'] ?? '';
    
    if (!$ep_id || !$judge_id || !$event_id) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required parameters: ep_id, judge_id, event_id']);
        exit;
    }
    
    // Get event scoring format and diversity rules
    $format_stmt = $pdo->prepare("SELECT scoring_format FROM events WHERE id = ?");
    $format_stmt->execute([$event_id]);
    $event = $format_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        http_response_code(404);
        echo json_encode(['error' => 'Event not found']);
        exit;
    }
    
    $diversity_rules = [];
    $scoring_format = null;
    
    if (!empty($event['scoring_format'])) {
        try {
            $scoring_format = json_decode($event['scoring_format'], true);
            if (isset($scoring_format['diversity_rules']) && is_array($scoring_format['diversity_rules'])) {
                $diversity_rules = $scoring_format['diversity_rules'];
            }
        } catch (Exception $e) {
            // Invalid JSON, continue with empty rules
        }
    }
    
    if (empty($diversity_rules)) {
        echo json_encode([
            'compliance' => true,
            'message' => 'No diversity rules defined for this event',
            'rules_checked' => 0,
            'details' => []
        ]);
        exit;
    }
    
    // Get all scores for this participant and judge
    $scores_stmt = $pdo->prepare("
        SELECT r.run_number, s.figures_json, s.score_value, s.status, s.created_at
        FROM scores s
        JOIN runs r ON s.run_id = r.id
        JOIN event_participants ep ON r.event_participant_id = ep.id
        WHERE ep.id = ? AND s.judge_id = ?
        ORDER BY r.run_number ASC
    ");
    $scores_stmt->execute([$ep_id, $judge_id]);
    $scores = $scores_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Parse figure selections from each score
    $figure_history = []; // { run_number: { category: [items] } }
    $validation_history = []; // Track client-side validation results
    
    foreach ($scores as $score) {
        $run_num = $score['run_number'];
        $figure_history[$run_num] = [];
        
        if (!empty($score['figures_json'])) {
            try {
                $figures_data = json_decode($score['figures_json'], true);
                
                // Handle new format with validation metadata
                if (isset($figures_data['figures'])) {
                    $figure_history[$run_num] = $figures_data['figures'];
                    
                    // Store validation metadata if available
                    if (isset($figures_data['validation'])) {
                        $validation_history[$run_num] = $figures_data['validation'];
                    }
                } else {
                    // Handle old format (direct figure data)
                    $figure_history[$run_num] = $figures_data;
                }
            } catch (Exception $e) {
                // Invalid JSON, treat as no figures
                $figure_history[$run_num] = [];
            }
        }
    }
    
    // Check diversity rules compliance
    $compliance_results = [];
    $overall_compliance = true;
    
    foreach ($diversity_rules as $rule) {
        $rule_type = $rule['rule_type'] ?? '';
        $scope = $rule['scope'] ?? 'run';
        $group = $rule['group_name'] ?? $rule['group'] ?? '';
        $min_distinct = intval($rule['min_distinct'] ?? 0);
        $is_optional = (bool)($rule['is_optional'] ?? false);
        
        if (empty($group) || $min_distinct <= 0) {
            continue;
        }
        
        $unique_items = [];
        $runs_analyzed = [];
        
        // Collect items based on scope
        if ($scope === 'run' || $scope === 'attempts' || $scope === 'attempt') {
            // Check each run individually
            foreach ($figure_history as $run_num => $run_figures) {
                $run_items = $run_figures[$group] ?? [];
                $unique_count = count(array_unique($run_items));
                $compliant = $unique_count >= $min_distinct;
                
                $runs_analyzed[] = [
                    'run_number' => $run_num,
                    'items_selected' => $run_items,
                    'unique_count' => $unique_count,
                    'compliant' => $compliant
                ];
                
                if (!$compliant && !$is_optional) {
                    $overall_compliance = false;
                }
            }
        } elseif ($scope === 'total' || $scope === 'aggregate') {
            // Check across all runs
            $all_items = [];
            foreach ($figure_history as $run_num => $run_figures) {
                $run_items = $run_figures[$group] ?? [];
                $all_items = array_merge($all_items, $run_items);
            }
            $unique_items = array_unique($all_items);
            $unique_count = count($unique_items);
            $compliant = $unique_count >= $min_distinct;
            
            $runs_analyzed[] = [
                'scope' => 'aggregate',
                'all_items' => $all_items,
                'unique_items' => $unique_items,
                'unique_count' => $unique_count,
                'compliant' => $compliant
            ];
            
            if (!$compliant && !$is_optional) {
                $overall_compliance = false;
            }
        }
        
        $compliance_results[] = [
            'rule_type' => $rule_type,
            'scope' => $scope,
            'group' => $group,
            'min_distinct' => $min_distinct,
            'is_optional' => $is_optional,
            'analysis' => $runs_analyzed,
            'rule_compliant' => !in_array(false, array_column($runs_analyzed, 'compliant'))
        ];
    }
    
    // Compile response
    $response = [
        'compliance' => $overall_compliance,
        'rules_checked' => count($diversity_rules),
        'participant_id' => $ep_id,
        'judge_id' => $judge_id,
        'event_id' => $event_id,
        'heat_number' => $heat_number,
        'scores_analyzed' => count($scores),
        'figure_history' => $figure_history,
        'validation_history' => $validation_history,
        'rule_details' => $compliance_results,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    // Add summary message
    if ($overall_compliance) {
        $response['message'] = 'All diversity rules are compliant';
    } else {
        $failed_rules = array_filter($compliance_results, function($rule) {
            return !$rule['rule_compliant'] && !$rule['is_optional'];
        });
        $response['message'] = 'Diversity rule violations found: ' . count($failed_rules) . ' mandatory rules failed';
        $response['failed_rules'] = array_values($failed_rules);
    }
    
    echo json_encode($response, JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Server error: ' . $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}
?>
