<?php
declare(strict_types=1);
// php server/tests/run.php
define('ALLIANTIES_NO_SESSION', true);
define('ALLIANTIES_TEST_SUITE', true);
require dirname(__DIR__) . '/lib/bootstrap.php';
require dirname(__DIR__) . '/lib/Store.php';

require __DIR__ . '/engine_test.php';

$failed = (int) ($GLOBALS['engine_failed'] ?? 0);
$passed = (int) ($GLOBALS['engine_passed'] ?? 0);

function expect2(bool $cond, string $msg): void
{
    global $failed, $passed;
    if ($cond) {
        $passed++;
        echo "  ok  $msg\n";
    } else {
        $failed++;
        echo "  FAIL  $msg\n";
    }
}

$tmp = sys_get_temp_dir() . '/allianties-test-' . bin2hex(random_bytes(6));
mkdir($tmp, 0775, true);
putenv('ALLIANTIES_DATA_DIR=' . $tmp);
// localDev() looks at HTTP_HOST — not set in CLI. debug_advance checks localDev.
$_SERVER['HTTP_HOST'] = '127.0.0.1';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

echo "Store: lobby, join, start, actions, sync\n";
$store = Store::open($tmp);

$a = $store->createLobby('local:test_user_1', 'Alice', 'images/avatars/test_user_1.svg', []);
expect2(isset($a['id'], $a['code']), 'create lobby');
expect2($a['status'] === 'lobby', 'status lobby');
expect2(strlen($a['code']) === 6, '6-char code: ' . $a['code']);
expect2($a['rules']['jury'] === true, 'jury on');
expect2($a['rules']['shrinking_arena'] === false, 'shrink off');
expect2($a['rules']['ceasefire'] === false, 'ceasefire off');

try {
    $store->startGame('local:test_user_1', $a['id']);
    expect2(false, 'start alone');
} catch (RuntimeException $e) {
    expect2($e->getMessage() === 'min_players', 'start alone refused');
}

$b = $store->joinByCode('local:test_user_2', 'Bob', 'images/avatars/test_user_2.svg', $a['code']);
expect2(count($b['players']) === 2, 'Bob joined');
expect2($b['id'] === $a['id'], 'same lobby');

// Case-insensitive join of already-present player (re-open).
$again = $store->joinByCode('local:test_user_2', 'Bob', null, strtolower($a['code']));
expect2(count($again['players']) === 2, 're-join is idempotent');

try {
    $store->startGame('local:test_user_2', $a['id']);
    expect2(false, 'non-host start');
} catch (RuntimeException $e) {
    expect2($e->getMessage() === 'not_host', 'non-host refused');
}

// Only the host may change the rules (server-side, 403).
$before = $store->load($a['id'])['rules'];
try {
    $store->setRules('local:test_user_2', $a['id'], ['jury' => false, 'ap_loot' => true]);
    expect2(false, 'non-host setRules must throw');
} catch (RuntimeException $e) {
    expect2($e->getMessage() === 'not_host', 'non-host setRules refused: not_host');
    expect2(apiHttpStatus($e->getMessage()) === 403, 'not_host maps to HTTP 403');
}
expect2($store->load($a['id'])['rules'] === $before, 'rules unchanged after refused non-host update');
expect2(apiHttpStatus('login') === 401 && apiHttpStatus('csrf') === 403 && apiHttpStatus('no_ap') === 400, 'other status codes unchanged');

$g = $store->setRules('local:test_user_1', $a['id'], [
    'jury' => true,
    'shrinking_arena' => true,
    'shrink_interval_days' => 3,
    'ceasefire' => true,
    'ceasefire_ranges' => [['start' => '22:00', 'end' => '06:00']],
]);
expect2($g['rules']['shrinking_arena'] === true, 'host set shrink on');
expect2($g['rules']['shrink_interval_days'] === 3, 'interval 3');
expect2($g['rules']['ceasefire'] === true, 'ceasefire on');
expect2(count($g['rules']['ceasefire_ranges']) === 1, 'one range stored');

$g = $store->startGame('local:test_user_1', $a['id']);
expect2($g['status'] === 'running', 'started');
expect2($g['players'][0]['ap'] === 1, '1 AP at start');

$view1 = $store->view($g, 'local:test_user_1');
expect2($view1['status'] === 'running', 'view running');
expect2(isset($view1['legal']['move']), 'legal moves in view');
expect2($view1['version'] >= 1, 'has version');
expect2(isset($view1['server_now']), 'has server_now');
expect2($view1['timezone'] === 'Europe/Amsterdam', 'timezone');

// Sync: same version → no game payload
$sync = $store->sync('local:test_user_1', $a['id'], $view1['version']);
expect2($sync['changed'] === false, 'unchanged sync');
expect2(!isset($sync['game']), 'no full state when unchanged');
expect2(isset($sync['next_distribution_at'], $sync['server_now']), 'lightweight fields present');

// Alice moves
$legal = Engine::legal($g, 'local:test_user_1', $store->now());
expect2(!empty($legal['move']), 'Alice can move');
$t = $legal['move'][0];
$g = $store->act('local:test_user_1', $a['id'], ['type' => 'move', 'x' => $t['x'], 'y' => $t['y']]);
expect2($g['players'][0]['ap'] === 0, 'AP spent');
$view2 = $store->view($g, 'local:test_user_1');
$sync = $store->sync('local:test_user_2', $a['id'], $view1['version']);
expect2($sync['changed'] === true, 'Bob sees a change');
expect2(isset($sync['game']['events']), 'full state on change');
expect2($sync['game']['players'][0]['x'] === $t['x'], 'Bob sees Alice’s new position');

// Notes privacy through present
$g = $store->setNote('local:test_user_1', $a['id'], 'local:test_user_2', 'suspicious');
$va = $store->view($g, 'local:test_user_1');
$vb = $store->view($g, 'local:test_user_2');
$noteA = '';
$noteB = '';
foreach ($va['players'] as $p) {
    if ($p['id'] === 'local:test_user_2') {
        $noteA = $p['note'];
    }
}
foreach ($vb['players'] as $p) {
    if ($p['id'] === 'local:test_user_2') {
        $noteB = $p['note'];
    }
}
expect2($noteA === 'suspicious', 'Alice sees her note');
expect2($noteB === '', 'Bob does not');

$g = $store->addMessage('local:test_user_1', $a['id'], 'local:test_user_2', 'hi bob');
$va = $store->view($g, 'local:test_user_1');
$vb = $store->view($g, 'local:test_user_2');
expect2(count($va['messages']) === 1, 'Alice sees message');
expect2(count($vb['messages']) === 1 && $vb['messages'][0]['text'] === 'hi bob', 'Bob sees message');

// Third player cannot join after start
try {
    $store->joinByCode('local:test_user_3', 'Cara', null, $a['code']);
    expect2(false, 'join after start');
} catch (RuntimeException $e) {
    expect2($e->getMessage() === 'game_started', 'join after start refused');
}

// Locale
$loc = $store->setLocale('local:test_user_1', 'nl');
expect2($loc === 'nl', 'locale stored');
expect2($store->locale('local:test_user_1') === 'nl', 'locale read');
$loc = $store->setLocale('local:test_user_1', 'zh-Hans');
expect2($loc === 'zh', 'zh-Hans normalised to zh');

// List
$list = $store->listFor('local:test_user_1');
expect2(count($list) === 1 && $list[0]['status'] === 'running', 'listed running game');

// Concurrent-ish: two IMMEDIATE transactions in sequence (same process)
$g = $store->createLobby('local:test_user_3', 'Cara', null, ['jury' => false]);
$store->joinByCode('local:test_user_4', 'Dan', null, $g['code']);
$g = $store->startGame('local:test_user_3', $g['id']);
$store->act('local:test_user_3', $g['id'], ['type' => 'surrender']);
$g = $store->present('local:test_user_4', $g['id']);
expect2($g['status'] === 'finished' && $g['winner_id'] === 'local:test_user_4', 'Dan wins after Cara surrenders');

// Unknown code
try {
    $store->joinByCode('local:test_user_1', 'Alice', null, 'XXXXXX');
    expect2(false, 'unknown code');
} catch (RuntimeException $e) {
    expect2($e->getMessage() === 'unknown_code', 'unknown_code');
}

// Anti-race: nested mutate is fine (txDepth); invalid action rolls back AP
$lobby = $store->createLobby('local:test_user_5', 'Eve', null, []);
$store->joinByCode('local:test_user_6', 'Fay', null, $lobby['code']);
$g = $store->startGame('local:test_user_5', $lobby['id']);
$apBefore = $g['players'][0]['ap'];
try {
    $store->act('local:test_user_5', $lobby['id'], ['type' => 'shoot', 'target' => 'nobody']);
    expect2(false, 'bad shoot');
} catch (RuntimeException $e) {
    expect2($e->getMessage() === 'out_of_range', 'bad shoot refused: ' . $e->getMessage());
}
$g = $store->load($lobby['id']);
expect2((int) $g['players'][0]['ap'] === $apBefore, 'AP unchanged after refused action (rollback)');


echo "safeNext\n";
expect2(safeNext(null) === null, 'null next');
expect2(safeNext('') === null, 'empty next');
expect2(safeNext('index.html') === 'index.html', 'plain path');
expect2(safeNext('index.html?join=AQBYH9') === 'index.html?join=AQBYH9', 'join query with =');
expect2(safeNext('index.html?join=AQBYH9&from=invite') === 'index.html?join=AQBYH9&from=invite', 'ampersand');
expect2(safeNext('index.html?join=ABC#frag') === 'index.html?join=ABC#frag', 'hash fragment');
expect2(safeNext('https://evil.example') === null, 'rejects scheme');
expect2(safeNext('//evil.example') === null, 'rejects protocol-relative');
expect2(safeNext('/etc/passwd') === null, 'rejects absolute path');
expect2(safeNext('index.html\\x') === null, 'rejects backslash');

echo "\nTotal passed: $passed  Failed: $failed\n";

// Cleanup
$files = glob($tmp . '/*');
if (is_array($files)) {
    foreach ($files as $f) {
        @unlink($f);
    }
}
@rmdir($tmp);

exit($failed > 0 ? 1 : 0);
