<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');

ini_set('display_errors', 0);
error_reporting(0);

define('CRAFTY_URL',   'https://craft.ipv6.nix.roulaise.net');
define('CRAFTY_TOKEN', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJpYXQiOjE3NzczMDIwNjIsInRva2VuX2lkIjoxfQ.DXFKO4aim-nJ_Wyn-o3qMaVyv6AP3aCoAYukR-uQels');

// Ports connus → clé logique
const PORT_MAP = [9191 => 'mc1', 9292 => 'mc2'];

function craftyGet(string $path): ?array {
    $ch = curl_init(CRAFTY_URL . $path);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . CRAFTY_TOKEN],
    ]);
    $body = curl_exec($ch);
    curl_close($ch);
    return $body ? json_decode($body, true) : null;
}

// Extraire -Xmx depuis la commande d'exécution → retourne en Mio
function extractXmx(string $cmd): ?int {
    if (preg_match('/-Xmx(\d+)([GgMm])/i', $cmd, $m)) {
        return strtolower($m[2]) === 'g'
            ? (int)$m[1] * 1024
            : (int)$m[1];
    }
    return null;
}

// 1. Lister les serveurs
$list = craftyGet('/api/v2/servers');
if (!$list || ($list['status'] ?? '') !== 'ok') {
    echo json_encode(['success' => false, 'error' => 'Crafty unreachable']);
    exit;
}

$result = [];

foreach ($list['data'] as $srv) {
    $uuid = $srv['server_id'];

    // Stats de ce serveur
    $stats = craftyGet("/api/v2/servers/{$uuid}/stats");
    if (!$stats || ($stats['status'] ?? '') !== 'ok') continue;
    $d = $stats['data'];

    // Identifier la clé logique par port
    $port = (int)($d['server_port'] ?? $srv['server_port'] ?? 0);
    $key  = PORT_MAP[$port] ?? null;

    // Fallback par nom si port inconnu
    if (!$key) {
        $name = strtolower($d['server_name'] ?? $srv['server_name'] ?? '');
        if (str_contains($name, '#1') || str_contains($name, 'mc1') || str_contains($name, 'forge'))      $key = 'mc1';
        elseif (str_contains($name, '#2') || str_contains($name, 'mc2') || str_contains($name, 'fabric')) $key = 'mc2';
        else $key = $uuid;
    }

    // RAM utilisée : Crafty retourne en octets
    $ramUsed = isset($d['mem']) ? (int)round($d['mem'] / 1024 / 1024) : null;

    // RAM allouée : extraire -Xmx depuis execution_command
    $cmd      = $d['execution_command'] ?? $srv['execution_command'] ?? '';
    $ramAlloc = extractXmx($cmd);

    $result[$key] = [
        'uuid'        => $uuid,
        'name'        => $d['server_name']  ?? $srv['server_name'] ?? $uuid,
        'port'        => $port,
        'running'     => (bool)($d['running']  ?? false),
        'players'     => (int)($d['online']    ?? 0),
        'max_players' => (int)($d['max']       ?? 0),
        'ram_used'    => $ramUsed,
        'ram_alloc'   => $ramAlloc,
        'cpu'         => isset($d['cpu']) ? round((float)$d['cpu'], 1) : null,
    ];
}

echo json_encode(['success' => true, 'servers' => $result], JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
?>
