<?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')), 1 / 9), 'Aurel power 1/9 (gravity 2 since t1199)');
expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60 - 0.55 / 9), 'Aurel miss ~53.9%');
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')) === 10, 'Aurel displayed Power 10');

echo "\nGravity minimum 2 (t1199)\n";
foreach (Planets::all() as $pl) {
    expect((float) $pl['jumpsToClear'] >= 2.0, 'catalog gravity >= 2: ' . $pl['id']);
}
foreach (['aurel', 'lunara', 'zephyr'] as $pid) {
    expect(almostEqual((float) Planets::byId($pid)['jumpsToClear'], 2.0), "$pid raised to 2.0");
}
expect(Planets::GRAVITY_MIN === 2.0 && Planets::GRAVITY_MAX === 4.0, 'gravity range constants');
expect(almostEqual(Planets::clampGravity(1.0), 2.0) && almostEqual(Planets::clampGravity(3.3), 3.3) && almostEqual(Planets::clampGravity(9), 4.0), 'clampGravity');
$tdG = Planets::displayValues(['jumpsToClear' => 4, 'fallTime' => 3, 'riseTime' => 1.5]);
expect(almostEqual($tdG['gravity'], 29.43) && $tdG['gravityPct'] === 300, 'gravity 4 shows 300% / 29.43 g');
expect(Planets::displayValues(Planets::byId('terra'))['gravityPct'] === 100, 'Terra 100%');
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 - 0.55 / 9), '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');

echo "Custom planet gravity clamp (t1199)\n";
$low = $ptsStore->saveCustomPlanet($u, [
    'name' => 'Lowgrav', 'people' => 'Floaters',
    'jumpsToClear' => 1, 'fallTime' => 3, 'riseTime' => 1.5,
    'colors' => $terraIds,
]);
expect(almostEqual((float) $low['jumpsToClear'], 2.0), 'saving gravity 1 stores 2');
$rawPdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
$rawPdo->exec("UPDATE custom_planets SET jumps_to_clear = 1.2 WHERE id = '" . $low['id'] . "'");
$lowList = array_values(array_filter($ptsStore->listCustomPlanets($u), fn($pl) => $pl['id'] === $low['id']));
expect(count($lowList) === 1 && almostEqual((float) $lowList[0]['jumpsToClear'], 2.0), 'an old row with 1.2 loads as 2');
$ptsStore->deleteCustomPlanet($u, $low['id']);


echo "Last chosen planet (t1196)\n";
expect($ptsStore->lastPlanet($u) === null, 'no last planet stored yet');
expect($ptsStore->profilePayload($u)['last_planet'] === null, 'payload last_planet null');
expect($ptsStore->setLastPlanet($u, 'terra') === 'terra', 'standard planet saved');
expect($ptsStore->lastPlanet($u) === 'terra', 'standard planet read back');
$ptsStore->setLastPlanet($u, $snap['id']);
expect($ptsStore->profilePayload($u)['last_planet'] === $snap['id'], 'own custom planet saved and in payload');
foreach (['', 'nope', str_repeat('x', 80)] as $bad) {
    try { $ptsStore->setLastPlanet($u, $bad); expect(false, 'bad planet accepted: ' . $bad); }
    catch (RuntimeException $e) { expect(true, 'bad planet refused: ' . substr($bad, 0, 8)); }
}
try { $ptsStore->setLastPlanet($v, $snap['id']); expect(false, 'other user may not pick my custom planet'); }
catch (RuntimeException $e) { expect(true, "someone else's custom planet refused"); }
expect($ptsStore->lastPlanet($u) === $snap['id'], 'refused writes keep the old value');

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->lastPlanet($u) === null, "deleted custom planet → last_planet falls back to null (t1196)");
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');

// t1278: a rematch in the same (reset) lobby must award again, otherwise
// the client's reward tally sees before === after and skips the count.
echo "Online rematch awards (t1278)\n";
$uR = 'local:rematch_a';
$vR = 'local:rematch_b';
$ptsStore->touchProfile($uR, 'Ra', null);
$ptsStore->touchProfile($vR, 'Rb', null);
$lobR = $ptsStore->createLobby($uR, 'Ra', 0.0, 'terra');
$ptsStore->joinLobby($vR, 'Rb', $lobR['code']);
$ptsStore->setReady($uR, true);
$ptsStore->setReady($vR, true);
$start1 = $ptsStore->startGame($uR);
expect(!empty($start1['started']), 'first match has a started timestamp');
$ptsStore->viewFor($uR, null, 90, false, []);
$ptsStore->viewFor($vR, null, 40, true, []);
expect($ptsStore->lifetimePoints($uR) === 90, 'match 1 winner awarded 90 (got ' . $ptsStore->lifetimePoints($uR) . ')');
expect($ptsStore->lifetimePoints($vR) === 40, 'match 1 loser awarded 40');
$lobAfter1 = $ptsStore->lobbyForUser($uR);
expect(($lobAfter1['status'] ?? '') === 'finished', 'lobby finished after last player is out');
expect($ptsStore->onlineAwardedFor($uR, $lobAfter1) === 90, 'winner online_awarded is 90');
expect($ptsStore->onlineAwardedFor($vR, $lobAfter1) === 40, 'loser online_awarded is 40');
$key1 = $ptsStore->onlineAwardKey($lobAfter1, $uR);
expect(strpos($key1, ':' . (int) $start1['started'] . ':') !== false, 'award key includes match start');

// Same match is idempotent under the new key too.
$ptsStore->viewFor($uR, null, 90, false, []);
expect($ptsStore->lifetimePoints($uR) === 90, 'same match stays idempotent');

$ptsStore->testNow = ((int) ($lobAfter1['finished'] ?? time())) + METEORS_PODIUM_SECONDS + 1;
$ptsStore->viewFor($uR);
$lobWait = $ptsStore->lobbyForUser($uR);
expect(($lobWait['status'] ?? '') === 'waiting', 'lobby resets after the podium');
expect($ptsStore->onlineAwardedFor($uR, $lobWait) === null, 'waiting lobby has no current award');

$ptsStore->setReady($uR, true);
$ptsStore->setReady($vR, true);
$start2 = $ptsStore->startGame($uR);
expect((int) $start2['started'] !== (int) $start1['started'], 'rematch gets a new started time');
$beforeRematchU = $ptsStore->lifetimePoints($uR);
$beforeRematchV = $ptsStore->lifetimePoints($vR);
$ptsStore->viewFor($uR, null, 70, false, []);
$ptsStore->viewFor($vR, null, 25, true, []);
expect($ptsStore->lifetimePoints($uR) === $beforeRematchU + 70, 'rematch winner is awarded again (got ' . $ptsStore->lifetimePoints($uR) . ')');
expect($ptsStore->lifetimePoints($vR) === $beforeRematchV + 25, 'rematch loser is awarded again');
$lobAfter2 = $ptsStore->lobbyForUser($uR);
expect($ptsStore->onlineAwardedFor($uR, $lobAfter2) === 70, 'rematch online_awarded is the new score, not the first');

// Mid-podium old-key compatibility: a first-match award stored under the
// pre-t1278 key must not be granted a second time after deploy.
$uOld = 'local:oldkey_a';
$vOld = 'local:oldkey_b';
$ptsStore->touchProfile($uOld, 'Oa', null);
$ptsStore->touchProfile($vOld, 'Ob', null);
$lobOld = $ptsStore->createLobby($uOld, 'Oa', 0.0, 'terra');
$ptsStore->joinLobby($vOld, 'Ob', $lobOld['code']);
$ptsStore->setReady($uOld, true);
$ptsStore->setReady($vOld, true);
$stOld = $ptsStore->startGame($uOld);
$ptsStore->viewFor($uOld, null, 15, false, []);
// Pretend the current match was already awarded with the old lobby-only key
// (as a live lobby would be, mid-podium, right after deploy).
$ptsStore->awardPoints($uOld, 15, 'online:' . $stOld['id'] . ':' . $uOld, 'online');
expect($ptsStore->lifetimePoints($uOld) === 15, 'seeded old-key award');
$ptsStore->viewFor($vOld, null, 5, true, []);
expect($ptsStore->lifetimePoints($uOld) === 15, 'old key for this same match is not awarded twice (got ' . $ptsStore->lifetimePoints($uOld) . ')');
expect($ptsStore->lifetimePoints($vOld) === 5, 'opponent still gets the new-key award');
$ptsStore->testNow = null;

$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 "Leaderboard (t1247)\n";
expect(safeAvatarUrl(null) === null, 'null avatar rejected');
expect(safeAvatarUrl('javascript:alert(1)') === null, 'javascript avatar rejected');
expect(safeAvatarUrl('https://auth.timfalken.com/avatar/1?v=2') === 'https://auth.timfalken.com/avatar/1?v=2', 'https avatar kept');
expect(safeAvatarUrl('/avatar/1') === '/avatar/1', 'same-origin path kept');
$parsed = parseAuthFriends([
    'friends' => [
        ['id' => 2, 'username' => 'ada', 'avatar_url' => 'https://auth.timfalken.com/avatar/2?v=3'],
        ['id' => 'nope', 'username' => 'bad'],
        ['id' => 0, 'username' => 'zero'],
        'not-an-array',
        ['id' => 3, 'username' => 'bob'],
    ],
]);
expect(count($parsed) === 2, 'parseAuthFriends keeps two valid friends');
expect($parsed[0]['id'] === 'auth:2' && $parsed[0]['name'] === 'ada', 'first friend id+name');
expect($parsed[0]['avatar'] === 'https://auth.timfalken.com/avatar/2?v=3', 'first friend avatar');
expect($parsed[1]['id'] === 'auth:3' && $parsed[1]['name'] === 'bob' && $parsed[1]['avatar'] === null, 'second friend no avatar');
expect(parseAuthFriends(['friends' => []]) === [], 'empty friends list');
expect(parseAuthFriends(null) === [], 'invalid friends payload');
[$aid, $aname, $aav] = authIdentity(['id' => 7, 'username' => 'tim', 'avatar_url' => 'https://auth.timfalken.com/avatar/7?v=1']);
expect($aid === 'auth:7' && $aname === 'tim' && $aav === 'https://auth.timfalken.com/avatar/7?v=1', 'authIdentity includes avatar_url');
expect(localTestFriends('local:test_user_1')[0]['id'] === 'local:test_user_2', 'local test_user_1 is friends with test_user_2');
expect(localTestFriends('local:test_user_2')[0]['id'] === 'local:test_user_1', 'and the other way around');
expect(localTestFriends('auth:7') === [], 'real accounts have no local test friends');

$lbDir = $tmp . '/leaderboard';
mkdir($lbDir, 0775, true);
$lb = Store::open($lbDir);
for ($i = 1; $i <= 12; $i++) {
    $uid = 'auth:' . (1000 + $i);
    $lb->touchProfile($uid, 'Player ' . sprintf('%02d', $i), 'https://auth.timfalken.com/avatar/' . (1000 + $i));
    $lb->awardPoints($uid, $i * 10, 'lb-' . $i, 'solo');
}
// nameless profile still appears, fallback name from the id
$lb->awardPoints('auth:1099', 5, 'lb-nameless', 'solo');
$top = $lb->topPlayers(10, 'auth:1012');
expect(count($top) === 10, 'global list is capped at 10 (got ' . count($top) . ')');
expect($top[0]['id'] === 'auth:1012' && $top[0]['points'] === 120 && $top[0]['rank'] === 1, 'highest score is first');
expect($top[0]['you'] === true, 'current player is flagged when in the top 10');
expect($top[0]['name'] === 'Player 12', 'name is stored on the profile');
expect($top[0]['avatar'] === 'https://auth.timfalken.com/avatar/1012', 'avatar is stored on the profile');
expect($top[9]['id'] === 'auth:1003' && $top[9]['points'] === 30 && $top[9]['you'] === false, '10th is Player 03 with 30 points');
$ids = array_column($top, 'id');
expect(!in_array('auth:1002', $ids, true) && !in_array('auth:1099', $ids, true), '11th and nameless (5 pts) stay off the top 10');
$below = $lb->topPlayers(10, 'auth:1001');
expect($below[0]['you'] === false && !in_array(true, array_column($below, 'you'), true), 'viewer outside the top 10 is not flagged');

$lb->touchProfile('auth:4000', 'Zero Points', null);
$withZero = $lb->topPlayers(50);
expect(!in_array('auth:4000', array_column($withZero, 'id'), true), 'global tab hides players with 0 points');
expect(array_reduce($withZero, fn($ok, $r) => $ok && $r['points'] > 0, true), 'every global row has points');

// ties: same points, then name, then id
$lb->touchProfile('auth:2001', 'Cara', null);
$lb->touchProfile('auth:2002', 'Ada', null);
$lb->awardPoints('auth:2001', 7, 'tie-c', 'solo');
$lb->awardPoints('auth:2002', 7, 'tie-a', 'solo');
$tie = $lb->topPlayers(50);
$cara = null; $ada = null;
foreach ($tie as $row) {
    if ($row['id'] === 'auth:2001') { $cara = $row; }
    if ($row['id'] === 'auth:2002') { $ada = $row; }
}
expect($ada && $cara && $ada['points'] === 7 && $cara['points'] === 7, 'tied players both listed');
expect($ada['rank'] < $cara['rank'], 'tie broken by name (Ada before Cara)');

$friends = [
    ['id' => 'auth:1012', 'name' => 'From API', 'avatar' => 'https://auth.timfalken.com/avatar/from-api'],
    ['id' => 'auth:1005', 'name' => 'Player 05', 'avatar' => null],
    ['id' => 'auth:3001', 'name' => 'Never Played', 'avatar' => 'https://auth.timfalken.com/avatar/3001'],
];
$fl = $lb->friendsLeaderboard($friends, 10, 'auth:1099');
$flIds = array_column($fl, 'id');
expect(!in_array('auth:3001', $flIds, true), 'friends tab hides a friend with 0 points (never played)');
expect(array_reduce($fl, fn($ok, $r) => $ok && $r['points'] > 0, true), 'every friends row has points');
expect($fl[0]['id'] === 'auth:1012' && $fl[0]['points'] === 120 && $fl[0]['name'] === 'Player 12', 'friend with a profile uses stored name and points');
expect($fl[1]['id'] === 'auth:1005' && $fl[1]['points'] === 50, 'second friend by points');
expect($fl[2]['id'] === 'auth:1099' && $fl[2]['points'] === 5 && $fl[2]['you'] === true, 'viewer is ranked among friends when they have points');
expect(count($fl) === 3, 'friends tab is friends-with-points plus you (got ' . count($fl) . ')');

$onlyYou = $lb->friendsLeaderboard([], 10, 'auth:1012');
expect(count($onlyYou) === 1 && $onlyYou[0]['id'] === 'auth:1012' && $onlyYou[0]['you'] === true, 'empty friend list still shows you if you have points');
$zeroYou = $lb->friendsLeaderboard($friends, 10, 'auth:4000');
expect(!in_array('auth:4000', array_column($zeroYou, 'id'), true), 'viewer with 0 points is omitted like anyone else');
expect($lb->friendsLeaderboard([], 10, 'auth:4000') === [], 'no friends and 0 points → empty friends tab');

echo "Leaderboard names from auth (t1249)\n";
expect(isPlaceholderName('auth:3', '3') === true, 'name equal to the auth id is a placeholder');
expect(isPlaceholderName('auth:3', 'auth:3') === true, 'raw user id is a placeholder');
expect(isPlaceholderName('auth:3', '') === true, 'empty name is a placeholder');
expect(isPlaceholderName('auth:3', 'Ada') === false, 'a real username is not a placeholder');
expect(isPlaceholderName('local:test_user_1', 'test_user_1') === false, 'local test names are real');

// Existing profile with no stored name, like the live fallback "1" / "3".
$lb->awardPoints('auth:3', 40, 'lb-t1249-ada', 'solo');
$before = $lb->topPlayers(10, null);
$adaRow = null;
foreach ($before as $row) {
    if ($row['id'] === 'auth:3') { $adaRow = $row; }
}
expect($adaRow && $adaRow['name'] === '3', 'without auth data the display name falls back to the id (' . ($adaRow['name'] ?? '?') . ')');

$known = [
    'auth:3' => ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=2'],
    'auth:1012' => ['id' => 'auth:1012', 'name' => 'From Friends', 'avatar' => null],
];
$filled = $lb->applyIdentities($before, $known);
$adaFilled = null;
foreach ($filled as $row) {
    if ($row['id'] === 'auth:3') { $adaFilled = $row; }
}
expect($adaFilled && $adaFilled['name'] === 'Ada', 'applyIdentities replaces the placeholder with the friends-list name');
expect($adaFilled && $adaFilled['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'applyIdentities fills the avatar from auth');

$n = $lb->rememberIdentities(array_values($known));
expect($n >= 1, 'rememberIdentities backfills existing profiles (changed ' . $n . ')');
$after = $lb->topPlayers(50, null);
$adaStored = null;
foreach ($after as $row) {
    if ($row['id'] === 'auth:3') { $adaStored = $row; }
}
expect($adaStored && $adaStored['name'] === 'Ada', 'later reads (including guests) use the backfilled name');
expect($adaStored && $adaStored['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'backfilled avatar is stored');

// Does not create a profile for a friend who never played.
$beforeCount = $lb->topPlayers(50);
$lb->rememberIdentities([['id' => 'auth:9999', 'name' => 'Ghost', 'avatar' => null]]);
$afterCount = $lb->topPlayers(50);
expect(count($afterCount) === count($beforeCount), 'rememberIdentities does not invent profiles for friends who never played');
$ghost = false;
foreach ($afterCount as $row) {
    if ($row['id'] === 'auth:9999') { $ghost = true; }
}
expect($ghost === false, 'the never-played friend is not on the global board');

// A leftover placeholder in the store loses to the friends-list name.
$pdoLb = new PDO('sqlite:' . $lbDir . '/meteors.sqlite');
$pdoLb->exec("UPDATE profiles SET name = '3' WHERE user_id = 'auth:3'");
$fl = $lb->friendsLeaderboard([
    ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=9'],
], 10, 'auth:1012');
$adaRow = null;
foreach ($fl as $row) {
    if ($row['id'] === 'auth:3') { $adaRow = $row; }
}
expect($adaRow && $adaRow['name'] === 'Ada', 'friends tab prefers the auth name over a stored placeholder');
expect($fl[0]['id'] === 'auth:1012' && $fl[0]['you'] === true, 'viewer with more points ranks above that friend');

// Friends cache: fresh hit, stale miss, stale allowed on failure path.
$lb->writeFriendsCache('auth:7', [
    ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => null],
], 1000);
$hit = $lb->readFriendsCache('auth:7', 1000 + 30);
expect($hit && $hit[0]['name'] === 'Ada', 'fresh friends cache is reused');
$miss = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1);
expect($miss === null, 'stale friends cache is not reused by default');
$stale = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1, true);
expect($stale && $stale[0]['id'] === 'auth:3', 'stale cache can be used when auth is unavailable');

$apiSrc = (string) file_get_contents(dirname(__DIR__) . '/api.php');
expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a leaderboard action');
expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');
$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');
expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');
expect(strpos($bootSrc, "/api/profiles") !== false, 'leaderboard names also come from public GET /api/profiles');

echo "Auth locale claim (t1250)\n";
expect(normalizeAuthLocale('zh-Hans') === 'zh', 'zh-Hans maps to zh');
expect(normalizeAuthLocale('zh-hans') === 'zh', 'zh-hans maps to zh');
expect(normalizeAuthLocale('zh_CN') === 'zh', 'zh_CN maps to zh');
expect(normalizeAuthLocale('nl') === 'nl', 'nl stays nl');
expect(normalizeAuthLocale('en-US') === 'en', 'en-US falls back to en');
expect(normalizeAuthLocale('xx') === null, 'unknown claim is null');
expect(normalizeAuthLocale('') === null, 'empty claim is null');
expect(authLocaleFromPayload(['user' => ['locale' => 'zh-Hans']]) === 'zh', '/api/me user.locale is read');
expect(authLocaleFromPayload(['locale' => 'de']) === 'de', 'top-level locale is read');
expect(authNumericId('auth:15') === 15, 'auth:15 → 15');
expect(authNumericId('local:test_user_1') === null, 'local testers are not auth ids');

$locUser = 'local:test_user_1';
$locStore = Store::open($tmp . '/locale-t1250');
expect($locStore->locale($locUser) === null, 'new profile has no stored locale');
expect($locStore->localeExplicit($locUser) === false, 'new profile is not an explicit in-game choice');
expect($locStore->setLocale($locUser, 'zh-Hans') === 'zh', 'setLocale accepts zh-Hans');
expect($locStore->locale($locUser) === 'zh' && $locStore->localeExplicit($locUser) === true, 'in-game set_locale marks the choice explicit');
$payload = $locStore->profilePayload($locUser);
expect(!empty($payload['locale_explicit']) && $payload['locale'] === 'zh', 'profilePayload exposes locale_explicit');

echo "Public auth profiles (t1253)\n";
$parsed = parseAuthProfiles([
    'profiles' => [
        ['id' => 2, 'username' => 'daniqueaben', 'avatar_url' => null],
        ['id' => 3, 'username' => 'lucia'],
        ['id' => 15, 'username' => 'emma', 'avatar_url' => 'https://auth.timfalken.com/avatar/15?v=1'],
        ['id' => 'nope', 'username' => 'bad'],
        ['id' => 1, 'username' => ''],
        'x',
    ],
]);
expect(count($parsed) === 3, 'parseAuthProfiles keeps valid rows (got ' . count($parsed) . ')');
expect($parsed[0]['id'] === 'auth:2' && $parsed[0]['name'] === 'daniqueaben', 'id 2 → auth:2 / daniqueaben');
expect($parsed[2]['avatar'] === 'https://auth.timfalken.com/avatar/15?v=1', 'avatar_url is kept');

$pr = Store::open($tmp . '/profiles-t1253');
$pr->testNow = 5000;
$pr->awardPoints('auth:2', 10, 't1253-a', 'solo');
$pr->awardPoints('auth:3', 20, 't1253-b', 'solo');
$pr->awardPoints('auth:15', 1, 't1253-c', 'solo');
$calls = [];
$GLOBALS['METEORS_AUTH_GET'] = function (string $path, $token = null) use (&$calls) {
    $calls[] = $path;
    if (!str_starts_with($path, '/api/profiles?ids=')) {
        throw new RuntimeException('unexpected path ' . $path);
    }
    $q = substr($path, strlen('/api/profiles?ids='));
    $ids = array_map('intval', explode(',', $q));
    $names = [2 => 'daniqueaben', 3 => 'lucia', 15 => 'emma'];
    $rows = [];
    foreach ($ids as $id) {
        if (isset($names[$id])) {
            $rows[] = ['id' => $id, 'username' => $names[$id], 'avatar_url' => null];
        }
    }
    return ['profiles' => $rows];
};
$got = fetchAuthProfiles($pr, ['auth:2', 'auth:3', 'auth:15', 'local:test_user_1']);
expect(isset($got['auth:2'], $got['auth:3'], $got['auth:15']), 'fetchAuthProfiles returns all auth ids');
expect($got['auth:3']['name'] === 'lucia' && $got['auth:2']['name'] === 'daniqueaben' && $got['auth:15']['name'] === 'emma', 'usernames from /api/profiles');
expect(count($calls) === 1, 'one batched /api/profiles request (got ' . count($calls) . ')');
expect(!str_contains($calls[0], 'local:'), 'local testers are not sent to auth');
$calls = [];
$again = fetchAuthProfiles($pr, ['auth:3']);
expect($again['auth:3']['name'] === 'lucia' && $calls === [], 'fresh profiles cache is reused');
$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL + 1;
$calls = [];
fetchAuthProfiles($pr, ['auth:3']);
expect(count($calls) === 1, 'stale profiles cache is refetched');

// Auth down: stale cache still fills names; no cache keeps fallbacks.
$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL * 3;
$GLOBALS['METEORS_AUTH_GET'] = function () {
    throw new RuntimeException('auth down');
};
$stale = fetchAuthProfiles($pr, ['auth:3']);
expect($stale['auth:3']['name'] === 'lucia', 'stale profiles cache is used when auth is unreachable');

$emptyStore = Store::open($tmp . '/profiles-t1253-empty');
$emptyStore->testNow = 1;
$down = fetchAuthProfiles($emptyStore, ['auth:9']);
expect($down === [], 'no cache and auth down → empty (caller keeps fallbacks)');

$board = $pr->topPlayers(10, null);
$filled = $pr->applyIdentities($board, $got);
$names = [];
foreach ($filled as $row) {
    $names[$row['id']] = $row['name'];
}
expect(($names['auth:3'] ?? '') === 'lucia', 'applyIdentities shows lucia instead of 3');
$pr->rememberIdentities(array_values($got));
$later = $pr->topPlayers(10, null);
$storedNames = [];
foreach ($later as $row) {
    $storedNames[$row['id']] = $row['name'];
}
expect(($storedNames['auth:2'] ?? '') === 'daniqueaben', 'backfill stores daniqueaben for later guests');
expect(($storedNames['auth:15'] ?? '') === 'emma', 'backfill stores emma');

$many = [];
for ($i = 1; $i <= 51; $i++) {
    $many[] = 'auth:' . $i;
}
$chunks = [];
$GLOBALS['METEORS_AUTH_GET'] = function (string $path) use (&$chunks) {
    $chunks[] = $path;
    return ['profiles' => []];
};
$fresh = Store::open($tmp . '/profiles-t1253-chunk');
fetchAuthProfiles($fresh, $many);
expect(count($chunks) === 2, 'more than 50 ids are split into two /api/profiles calls (got ' . count($chunks) . ')');
unset($GLOBALS['METEORS_AUTH_GET']);

$srcApi = (string) file_get_contents(dirname(__DIR__) . '/api.php');
expect(strpos($srcApi, 'auth_locale') !== false, 'me/poll expose auth_locale');
expect(strpos($srcApi, 'locale_explicit') !== false, 'me/poll expose locale_explicit');
$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');
expect(strpos($cbSrc, 'storeAuthLocale') !== false, 'callback stores the OIDC locale claim');

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);
