<?php
require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json');

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $gameId = $_GET['id'] ?? '';
    if (!$gameId) {
        http_response_code(400);
        echo json_encode(['error' => 'missing game id']);
        exit;
    }

    $res = supabase_rest('GET', "matches?id=eq.{$gameId}&select=*", [], $token);

    if ($res['status'] >= 200 && $res['status'] < 300 && !empty($res['data'])) {
        $game = $res['data'][0];

        // If analysis already cached in game_state, return it
        $gameState = $game['game_state'] ?? null;
        if (is_string($gameState)) {
            $gameState = json_decode($gameState, true);
        }
        $hasAnalysis = isset($gameState['analysis']) && !empty($gameState['analysis']);

        echo json_encode([
            'game' => $game,
            'has_analysis' => $hasAnalysis,
            'analysis' => $hasAnalysis ? $gameState['analysis'] : null
        ]);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'game not found']);
    }
    exit;
}

// POST requests
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

switch ($action) {
    case 'analyze':
        $gameId = $input['game_id'] ?? '';
        $positions = $input['positions'] ?? []; // Array of FEN strings

        if (!$gameId || empty($positions)) {
            http_response_code(400);
            echo json_encode(['error' => 'missing game_id or positions']);
            exit;
        }

        $evaluations = [];
        $apiUrl = STOCKFISH_API . '/api/chess/move';

        foreach ($positions as $index => $fen) {
            $payload = json_encode([
                'bot_id' => 'grandmaster',
                'fen' => $fen,
                'wtime' => 120000,
                'btime' => 120000
            ]);

            $ch = curl_init($apiUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'X-API-Key: ' . STOCKFISH_MGMT_KEY
            ]);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            unset($ch);

            if ($httpCode === 200) {
                $data = json_decode($response, true);
                $evaluations[] = [
                    'move_index' => $index,
                    'fen' => $fen,
                    'best_move' => $data['best_move'] ?? null,
                    'evaluation' => $data['evaluation'] ?? 0,
                    'depth' => $data['depth'] ?? 20
                ];
            } else {
                $evaluations[] = [
                    'move_index' => $index,
                    'fen' => $fen,
                    'best_move' => null,
                    'evaluation' => 0,
                    'depth' => 0,
                    'error' => true
                ];
            }

            // Small delay to avoid overwhelming the API
            if ($index < count($positions) - 1) {
                usleep(100000); // 100ms
            }
        }

        // Cache analysis in game_state
        $analysisData = [
            'evaluations' => $evaluations,
            'analyzed_at' => date('c')
        ];

        // Get existing game_state
        $gameRes = supabase_rest('GET', "matches?id=eq.{$gameId}&select=game_state", [], $token);
        $existingState = [];
        if (!empty($gameRes['data'][0]['game_state'])) {
            $existingState = $gameRes['data'][0]['game_state'];
            if (is_string($existingState)) {
                $existingState = json_decode($existingState, true) ?? [];
            }
        }
        $existingState['analysis'] = $analysisData;

        supabase_rest('PATCH', "matches?id=eq.{$gameId}", [
            'game_state' => json_encode($existingState)
        ], $token);

        echo json_encode([
            'ok' => true,
            'analysis' => $analysisData
        ]);
        break;

    case 'analyze_single':
        // Analyze a single position (used for real-time partial analysis)
        $fen = $input['fen'] ?? '';
        if (!$fen) {
            http_response_code(400);
            echo json_encode(['error' => 'missing fen']);
            exit;
        }

        $apiUrl = STOCKFISH_API . '/api/chess/move';
        $payload = json_encode([
            'bot_id' => 'grandmaster',
            'fen' => $fen,
            'wtime' => 120000,
            'btime' => 120000
        ]);

        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'X-API-Key: ' . STOCKFISH_MGMT_KEY
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        unset($ch);

        if ($httpCode === 200) {
            $data = json_decode($response, true);
            echo json_encode([
                'best_move' => $data['best_move'] ?? null,
                'evaluation' => $data['evaluation'] ?? 0,
                'depth' => $data['depth'] ?? 20
            ]);
        } else {
            http_response_code(502);
            echo json_encode(['error' => 'engine unavailable']);
        }
        break;

    case 'cache':
        $gameId = $input['game_id'] ?? '';
        $evaluations = $input['evaluations'] ?? [];

        if (!$gameId || empty($evaluations)) {
            http_response_code(400);
            echo json_encode(['error' => 'missing data']);
            exit;
        }

        $analysisData = [
            'evaluations' => $evaluations,
            'analyzed_at' => date('c')
        ];

        $gameRes = supabase_rest('GET', "matches?id=eq.{$gameId}&select=game_state", [], SUPABASE_SERVICE_KEY);
        $existingState = [];
        if (!empty($gameRes['data'][0]['game_state'])) {
            $existingState = $gameRes['data'][0]['game_state'];
            if (is_string($existingState)) {
                $existingState = json_decode($existingState, true) ?? [];
            }
        }
        $existingState['analysis'] = $analysisData;

        supabase_rest('PATCH', "matches?id=eq.{$gameId}", [
            'game_state' => json_encode($existingState)
        ], SUPABASE_SERVICE_KEY);

        echo json_encode(['ok' => true]);
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'invalid action']);
}
