<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/constants.php';

$token = requireAuth();
$input = getInput();
$fen = $input['fen'] ?? '';
$depth = intval($input['depth'] ?? 18);
$lines = intval($input['lines'] ?? 3);

if (!$fen) jsonError('fen is required');

$payload = json_encode(['fen' => $fen, 'depth' => min($depth, 25), 'lines' => min($lines, 5)]);

$ch = curl_init(STOCKFISH_API . '/api/chess/analyze');
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']);
curl_setopt($ch, CURLOPT_TIMEOUT, 35);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    $err = json_decode($response, true);
    jsonError($err['error'] ?? 'Analysis failed', $httpCode);
}

jsonResponse(json_decode($response, true));
