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

$failed = 0;
$passed = 0;

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

function almostEqual(float $a, float $b, float $eps = 1e-6): bool
{
    return abs($a - $b) <= $eps;
}

$tmp = sys_get_temp_dir() . '/meteors-test-' . bin2hex(random_bytes(6));
mkdir($tmp, 0775, true);
putenv('METEORS_DATA_DIR=' . $tmp);

echo "Login return target (t1193)\n";
expect(loginReturnTarget(null) === 'menu', 'no return param → main menu');
expect(loginReturnTarget('') === 'menu', 'empty return → main menu');
expect(loginReturnTarget('online') === 'online', 'return=online → online play');
expect(loginReturnTarget('https://evil.example/') === 'menu', 'unknown/URL value → main menu (no open redirect)');
expect(loginReturnTarget(['online']) === 'menu', 'array value → main menu');
expect(loginReturnPath('menu') === 'index.html', 'menu path has no online flag');
expect(loginReturnPath(null) === 'index.html', 'missing session value → menu');
expect(loginReturnPath('online') === 'index.html?online=1', 'online path opens the online panel');
$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');
expect(strpos($cbSrc, "index.html?online=1'") === false, 'callback no longer hard-codes ?online=1');
expect(strpos($cbSrc, 'loginReturnPath(') !== false, 'callback uses loginReturnPath');
$authSrc = (string) file_get_contents(dirname(__DIR__) . '/auth.php');
expect(strpos($authSrc, "loginReturnTarget(\$_GET['return']") !== false, 'auth.php stores the return target');

echo "Store: lobby and game\n";
$store = Store::open($tmp);

$a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);
expect(isset($a['id'], $a['code']), 'create lobby returns id and code');
expect($a['status'] === 'waiting', 'new lobby is waiting');
expect(strlen($a['code']) === 4, 'code is 4 characters');
expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');

$view = $store->viewFor('local:test_user_1');
expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');
expect($view['lobby']['can_start'] === false, 'cannot start alone');

try {
    $store->startGame('local:test_user_1');
    expect(false, 'start alone should throw');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());
}

$joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);
expect($joined['id'] === $a['id'], 'second player joins by code');
$view = $store->viewFor('local:test_user_1');
expect(count($view['lobby']['players']) === 2, 'two players in lobby');
expect($view['lobby']['can_start'] === false, 'cannot start until both ready');

$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$view = $store->viewFor('local:test_user_1');
expect($view['lobby']['all_ready'] === true, 'all ready');
expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');

$view2 = $store->viewFor('local:test_user_2');
expect($view2['lobby']['can_start'] === false, 'non-host cannot start');

try {
    $store->startGame('local:test_user_2');
    expect(false, 'non-host start should throw');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');
}

$started = $store->startGame('local:test_user_1');
expect($started['status'] === 'playing', 'game starts');

// Shots: force miss by using miss_chance 1.0 on a fresh lobby later.
// Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.
$results = $store->recordShots('local:test_user_1', [
    ['client_id' => 'c1', 'color' => 2],
    ['client_id' => 'c2', 'color' => -1],
]);
expect(count($results) === 2, 'two shot results');
expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');
expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');

// Incoming is delayed until deliver_at.
$inc = $store->viewFor('local:test_user_2');
$hits = array_filter($results, fn ($r) => !$r['miss']);
if ($hits) {
    expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');
} else {
    expect(true, 'all missed — no incoming expected');
}

// Fast-forward: rewrite deliver_at in the sqlite file.
$pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
$pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');
$inc = $store->viewFor('local:test_user_2');
$expectedHits = count($hits);
expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");
$inc2 = $store->viewFor('local:test_user_2');
expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');

// Elimination and podium.
$store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);
$view = $store->viewFor('local:test_user_1');
expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');
$ranks = $view['lobby']['rankings'];
expect(count($ranks) >= 2, 'rankings present');
$first = $ranks[0];
expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');
$second = $ranks[1];
expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');

// Podium wait: not yet reset.
$view = $store->viewFor('local:test_user_1');
expect($view['lobby']['status'] === 'finished', 'still finished during podium');

$pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));
$view = $store->viewFor('local:test_user_1');
expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');
expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');

// Host leave transfers host.
$store->leaveLobby('local:test_user_1');
$view = $store->viewFor('local:test_user_2');
expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');

// Mid-game leave counts as elimination.
$store->leaveLobby('local:test_user_2');
$b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
$store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$store->leaveLobby('local:test_user_2');
$view = $store->viewFor('local:test_user_1');
expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');
expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');

// Miss chance 1.0: all miss. Need a fresh game with 2 players.
// Leave leftover memberships.
$store->leaveLobby('local:test_user_1');
$c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);
$store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$store->testMissOverride = 1.0;
$allMiss = $store->recordShots('local:test_user_1', [
    ['client_id' => 'm1', 'color' => 0],
    ['client_id' => 'm2', 'color' => 1],
    ['client_id' => 'm3', 'color' => 2],
]);
$store->testMissOverride = null;
expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');

$d = null;
$store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');
$d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
$store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$store->testMissOverride = 0.0;
$allHit = $store->recordShots('local:test_user_1', [
    ['client_id' => 'h1', 'color' => 0],
    ['client_id' => 'h2', 'color' => 1],
]);
$store->testMissOverride = null;
expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'forced miss 0 → all hit the other player');

// Eliminated player is not a target.
$store->updateSnapshot('local:test_user_2', null, 0, true);
$none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);
// Game may already be finished; recordShots on finished returns [].
expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');


echo "\nPlanets and per-sender Power miss\n";
expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');
expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');
expect(almostEqual(Planets::power(Planets::byId('aurel')), 0.0), 'Aurel power 0');
expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel miss 60%');
expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
$td = Planets::displayValues(Planets::byId('terra'));
expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 44, 'Terra display g/d/F/Power');
expect(Planets::displayPower(Planets::byId('aurel')) === 0, 'Aurel displayed Power 0');
expect(Planets::displayPower(Planets::byId('cinder')) === 92, 'Cinder displayed Power 92 (5% miss)');
expect(Planets::displayValues(Planets::byId('cinder'))['power'] === 92, 'Cinder displayValues Power 92');

$store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');
$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
$presented = $store->presentLobby($pl, 'local:test_user_1');
$byId = [];
foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60), 'host miss from Aurel Power');
expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');

$store->setPlanet('local:test_user_1', 'wisp');
$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
foreach ($presented['players'] as $plr) {
    if ($plr['is_me']) {
        expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
    }
}

try {
    $store->setPlanet('local:test_user_1', 'no-such-world');
    expect(false, 'unknown planet must throw');
} catch (RuntimeException $e) {
    expect(true, 'unknown planet rejected');
}

$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$me = $store->member($pl['id'], 'local:test_user_1');
expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
$guest = $store->member($pl['id'], 'local:test_user_2');
expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
try {
    $store->setPlanet('local:test_user_1', 'terra');
    expect(false, 'setPlanet during play must throw');
} catch (RuntimeException $e) {
    expect(true, 'planet locked once the match starts');
}
$store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');

echo "\nshot_flights (t1125)\n";
$e = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
$store->joinLobby('local:test_user_2', 'test_user_2', $e['code']);
$store->joinLobby('local:test_user_3', 'test_user_3', $e['code']);
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->setReady('local:test_user_3', true);
$store->startGame('local:test_user_1');
$store->testMissOverride = 0.0;
$shots = $store->recordShots('local:test_user_1', [
    ['client_id' => 'f1', 'color' => 2, 'col' => 6, 'y' => 12.4],
]);
$store->testMissOverride = null;
expect(count($shots) === 1, 'one recorded shot');
expect(($shots[0]['from_id'] ?? null) === 'local:test_user_1', 'shot_results includes from_id');
expect(isset($shots[0]['age']) && almostEqual((float) $shots[0]['age'], 0.0), 'own result age is 0');

$view3 = $store->viewFor('local:test_user_3');
expect(isset($view3['shot_flights']) && is_array($view3['shot_flights']), 'viewFor exposes shot_flights');
$found = null;
foreach ($view3['shot_flights'] as $f) {
    if (($f['client_id'] ?? '') === 'f1') {
        $found = $f;
        break;
    }
}
expect($found !== null, 'third player sees the shot in shot_flights');
if ($found) {
    expect($found['from_id'] === 'local:test_user_1', 'shot_flights.from_id is the shooter');
    expect($found['target_id'] === 'local:test_user_2' || $found['target_id'] === 'local:test_user_3', 'hit lands on a living opponent');
    expect($found['miss'] === false, 'forced hit is not a miss');
    expect($found['age'] >= 0 && $found['age'] < 2.0, 'age is seconds since created');
    expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
    expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');
    expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');
    expect(($shots[0]['col'] ?? null) === 6, 'shot_results echoes launch col');
    expect(isset($shots[0]['y']) && abs((float) $shots[0]['y'] - 12.4) < 0.01, 'shot_results echoes launch y');
    expect(($found['col'] ?? null) === 6, 'shot_flights has launch col (t1136)');
    expect(isset($found['y']) && abs((float) $found['y'] - 12.4) < 0.01, 'shot_flights has launch y (t1136)');
}
// Incoming carries the same land_col (t1126).
$targetId = $found['target_id'] ?? $shots[0]['target_id'];
$pdoLand = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
$pdoLand->exec('UPDATE shots SET deliver_at = 0 WHERE client_id = "f1"');
$incLand = $store->viewFor($targetId);
$incHit = null;
foreach ($incLand['incoming'] as $row) {
    if (($row['client_id'] ?? '') === 'f1') {
        $incHit = $row;
        break;
    }
}
expect($incHit !== null, 'target receives incoming for the shot');
if ($incHit) {
    expect(($incHit['land_col'] ?? null) === $found['land_col'], 'incoming.land_col matches the flight');
}
$view1 = $store->viewFor('local:test_user_1');
expect(count($view1['shot_flights']) >= 1, 'shooter also sees shot_flights (client de-dupes)');
$store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');
$store->leaveLobby('local:test_user_3');


echo "\nBlocks registry and unlock thresholds\n";
require_once dirname(__DIR__) . '/lib/Blocks.php';
$allBlocks = Blocks::all();
expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
for ($i = 0; $i < 5; $i++) {
    expect(Blocks::threshold($i) === 0, "terra index $i is free");
}
expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
$prev = 500;
for ($i = 6; $i < count($allBlocks); $i++) {
    $t = Blocks::threshold($i);
    if ($t <= $prev) {
        expect(false, "threshold at $i should be > $prev, got $t");
        break;
    }
    $prev = $t;
}
expect($prev > 500, 'later thresholds grow');
expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
$terraIds = [];
foreach ($allBlocks as $i => $b) {
    if ($i >= 5) break;
    $terraIds[] = $b['id'];
}

echo "\nLifetime points, anti-cheat, custom planets\n";
$ptsStore = Store::open($tmp);
$u = 'local:designer_a';
$v = 'local:designer_b';
expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
expect($t1 === 200, 'first award adds 200');
$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
expect($t2 === 200, 'same award_key is idempotent');
$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
expect($t3 === 250, 'second key adds 50');

$ptsStore->testNow = 1_000_000;
$ses = $ptsStore->playBegin($u, 'solo');
expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
$ptsStore->testNow = 1_000_001;
$fin = $ptsStore->playFinish($u, $ses['token'], 9000);
expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
$again = $ptsStore->playFinish($u, $ses['token'], 9000);
expect(!empty($again['already']), 'second finish of same token is a no-op');

$ptsStore->testNow = 2_000_000;
$ses2 = $ptsStore->playBegin($u, 'offline');
$ptsStore->testNow = 2_000_010;
$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
expect($fin2['lifetime_points'] === 290, 'capped award is added');

$ptsStore->testNow = 3_000_000;
$ses3 = $ptsStore->playBegin($u, 'solo');
$ptsStore->testNow = 3_000_020;
$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
expect($fin3['awarded'] === 17, 'honest score under the cap is kept');

try {
    $ptsStore->saveCustomPlanet($u, [
        'name' => 'Lockworld', 'people' => 'Lockers',
        'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
        'colors' => array_merge($terraIds, ['rune-fehu']),
    ]);
    // 6 items? no that's 6. Use 4 terra + fehu
    expect(false, 'should not reach (wrong colors count would throw first)');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
        'invalid colors refused: ' . $e->getMessage());
}

try {
    $ptsStore->saveCustomPlanet($u, [
        'name' => 'Lockworld', 'people' => 'Lockers',
        'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
    ]);
    expect(false, 'locked block should throw');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
}

try {
    $ptsStore->saveCustomPlanet($u, [
        'name' => 'Ghost', 'people' => 'Ghosts',
        'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
    ]);
    expect(false, 'unknown block should throw');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
}

try {
    $ptsStore->saveCustomPlanet($u, [
        'name' => 'Twins', 'people' => 'Twins',
        'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
    ]);
    expect(false, 'duplicate block should throw');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
        'duplicate block refused: ' . $e->getMessage());
}

$snap = $ptsStore->saveCustomPlanet($u, [
    'name' => 'My World', 'people' => 'My People',
    'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
    'colors' => $terraIds,
]);
expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
expect($snap['custom'] === true, 'snapshot is marked custom');
expect($snap['name'] === 'My World', 'name stored');
expect(count($snap['colors']) === 5, 'five colors in snapshot');
expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
expect($snap['owner_id'] === $u, 'owner_id set');

$listed = $ptsStore->listCustomPlanets($u);
expect(count($listed) === 1, 'owner lists the planet');
expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');

try {
    $ptsStore->setPlanet($u, $snap['id']);
    expect(false, 'setPlanet without a lobby should throw');
} catch (RuntimeException $e) {
    expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
}

$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
$view = $ptsStore->viewFor($u);
$meP = $view['lobby']['players'][0]['planet'] ?? null;
expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
expect(!empty($meP['custom']), 'presented planet is custom');
expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');

$ptsStore->joinLobby($v, 'B', $lobby['code']);
$viewB = $ptsStore->viewFor($v);
$seen = null;
foreach ($viewB['lobby']['players'] as $plr) {
    if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
}
expect($seen !== null, 'other player sees the custom planet snapshot');
expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');

try {
    $ptsStore->setPlanet($v, $snap['id']);
    expect(false, 'cannot pick someone else\'s custom planet');
} catch (RuntimeException $e) {
    expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
}

$ptsStore->leaveLobby($u);
$ptsStore->leaveLobby($v);
$ptsStore->deleteCustomPlanet($u, $snap['id']);
expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');

// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
$snap2 = $ptsStore->saveCustomPlanet($u, [
    'name' => 'Frozen', 'people' => 'Ice',
    'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
    'colors' => $terraIds,
]);
$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
$ptsStore->joinLobby($v, 'B', $lobby2['code']);
$ptsStore->setReady($u, true);
$ptsStore->setReady($v, true);
$ptsStore->startGame($u);
$ptsStore->saveCustomPlanet($u, [
    'id' => $snap2['id'],
    'name' => 'Changed', 'people' => 'Ice',
    'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
    'colors' => $terraIds,
]);
$viewMid = $ptsStore->viewFor($v);
$midP = null;
foreach ($viewMid['lobby']['players'] as $plr) {
    if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
}
expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
$ptsStore->leaveLobby($u);
$ptsStore->leaveLobby($v);

// Online award is idempotent and server-side.
$u3 = 'local:online_award_a';
$v3 = 'local:online_award_b';
$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
$ptsStore->joinLobby($v3, 'B', $lob['code']);
$ptsStore->setReady($u3, true);
$ptsStore->setReady($v3, true);
$ptsStore->startGame($u3);
$ptsStore->viewFor($u3, null, 80, false, []);
$ptsStore->viewFor($u3, null, 80, true, []);
expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
$ptsStore->viewFor($u3, null, 999, true, []);
expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');

$ptsStore->setLocale($u, 'nl');
expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
try {
    $ptsStore->setLocale($u, 'xx');
    expect(false, 'unknown locale should throw');
} catch (RuntimeException $e) {
    expect(true, 'unknown locale refused');
}

echo "\nConfig helpers\n";


$cfg = config();
expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
expect(authConfigured() === false, 'auth is unconfigured without a secret');
putenv('METEORS_CLIENT_SECRET=test-secret-value');
// config file empty secret falls back to env
$cfg2 = config();
expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
putenv('METEORS_CLIENT_SECRET');

echo "\n$passed passed, $failed failed\n";

// cleanup
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $f) {
    $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
}
@rmdir($tmp);

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