<?php
declare(strict_types=1);

// Solo playthrough of Chapter 1 (using the prybar) and all of Chapter 2, run
// straight against the engine with a throwaway SQLite database.
//   php tests/solo_test.php            (prints PASS/FAIL lines)
//   php tests/solo_test.php -v         (also prints the full transcript)

$dir = sys_get_temp_dir() . '/nergmud-test-' . getmypid();
@mkdir($dir);
file_put_contents("$dir/config.php", "<?php return ['app_name'=>'NERGmud Two','world'=>'hollow_hill','base_path'=>'','dev_mode'=>true,"
    . "'secure_cookies'=>false,'trust_cloudflare_ip'=>false,'db'=>['dsn'=>'sqlite:$dir/t.sqlite','user'=>null,'pass'=>null]];");
putenv("NERGMUD_CONFIG=$dir/config.php");
require __DIR__ . '/../src/bootstrap.php';

use App\Db;
use App\Engine;
use App\World;

foreach (Db::schemaStatements() as $sql) {
    Db::pdo()->exec($sql);
}
World::seed();

$verbose = in_array('-v', $argv, true);
$fails = 0;
$pid = Db::insert('INSERT INTO players (name, pass_hash, room, created_at, last_seen) VALUES (?,?,?,?,?)', ['Solo', 'x', 'square', time(), time()]);

function cmd(string $c): string
{
    global $pid, $verbose;
    $out = Db::tx(function () use ($c, $pid) {
        $p = Db::one('SELECT id, name, room FROM players WHERE id = ?', [$pid]);
        return (new Engine($p))->run($c);
    });
    $text = implode("\n", array_map(fn($l) => $l['s'], $out['lines']));
    if ($verbose) {
        echo "> $c\n  " . str_replace("\n", "\n  ", $text) . "\n";
    }
    return $text;
}
function check(bool $ok, string $label): void
{
    global $fails;
    echo ($ok ? 'PASS ' : 'FAIL ') . $label . "\n";
    if (!$ok) { $fails++; }
}
function has(string $cmd, string $needle, string $label): string
{
    $t = cmd($cmd);
    check(str_contains($t, $needle), $label . ($t === '' ? '' : ''));
    if (!str_contains($t, $needle)) { echo "      got: " . str_replace("\n", ' / ', $t) . "\n"; }
    return $t;
}
function room(): string
{
    global $pid;
    return (string) Db::value('SELECT room FROM players WHERE id = ?', [$pid]);
}
function run(array $cmds): void { foreach ($cmds as $c) { cmd($c); } }

// ------------------------------------------------------------- Chapter 1, solo
has('look', 'brass plaque', 'start room mentions the plaque');
run(['w', 'take sickle', 'take apple', 'e', 'n', 'n']);
has('cut brambles', 'path opens north', 'cut brambles');
run(['s', 's', 'e', 'take torch', 'light torch', 'take rope', 'w']);
has('tie rope', 'climb down', 'tie rope to well');
run(['d', 'take key']);
has('take prybar', 'You take the prybar', 'prybar found at the bottom of the well');
run(['u', 's']);
has('open door', 'Stairs lead down', 'unlock crypt');
run(['d', 'take bell', 'w', 'n']);
has('push slab', 'slides aside', 'push slab solo with prybar in hand: it levers aside');
check(room() === 'collapsed_hall', 'still in collapsed hall');
run(['n', 'drop sickle', 'take moonstone', 's', 's', 'u']);
has('feed rat', 'waddles off', 'bribe the rat');
run(['e']);
has('put moonstone in hollow', 'settles', 'moonstone in hollow');
has('ring bell', 'Chapter 1 complete', 'chapter 1 complete');
check(World::isOn('deep_door'), 'deep door is open');

// ------------------------------------------------------------- Outskirts
run(['w', 'w', 's', 's', 'e', 'e']);
check(room() === 'mill_yard', 'reached the mill yard');
has('look', 'branch is jammed', 'mill wheel is stuck');
has('pry branch', 'begins to turn', 'pry the branch: mill turns');
has('take plank', 'You take the plank', 'take plank');
run(['u']);
has('read journal', 'second was the highest', 'miller\'s journal clue');
run(['d', 's']);
has('w', 'swollen shut', 'boathouse door stuck');
has('pry door', 'pops open', 'pry boathouse door');
run(['w']);
has('take oar', 'You take the oar', 'take oar');
run(['e', 'e']);
has('e', 'too wide', 'bridge gap blocks the way');
has('put plank on bridge', 'It holds', 'lay plank across the bridge');
run(['e', 'n']);
has('ring bell', 'this one comes last', 'standing stones clue');
run(['s', 's', 'e']);
has('read note', 'something sweet', 'hermit note');
has('open hive', 'Smoke would calm them', 'bees without smoke');
has('smoke hive', 'honeycomb', 'smoke hive with torch: honeycomb');
has('i', 'honeycomb', 'honeycomb in inventory');
run(['drop key', 'w', 'n', 'w', 'w', 'n', 'w', 'w', 's', 'ne']);
check(room() === 'inn', 'reached the inn');
has('ask marta', "Wenna's grave", 'ask Marta');
run(['d']);
has('open crate', 'brass gear', 'pry the cellar crate (auto prybar): brass gear');
has('open crate', 'empty now', 'crate is empty afterwards');

// ------------------------------------------------------------- Chapter 2: the Halls
run(['u', 'sw', 's', 'd', 'w']);
check(room() === 'deep_tunnel', 'back at the deep tunnel');
has('d', 'Deep Stair', 'down the deep stair');
run(['d']);
has('n', 'portcullis is down', 'portcullis blocks the hall');
has('turn winch', 'empty square socket', 'winch without a crank');
run(['w', 'drop bell', 'take crank', 'e']);
has('turn winch', 'portcullis rises', 'winch up the portcullis');
has('n', 'Great Hall', 'enter the Great Hall');
run(['drop crank', 'se']);
has('pull lever', 'missing', 'lift lever without the gear');
has('put gear in mechanism', 'tick', 'fit the brass gear');
has('pull lever', 'Bottom of the Shaft', 'ride the lift down');
run(['n']);
has('take glowcap', 'glowcap', 'pick a glowcap');
has('douse glowcap', 'glows all by itself', 'glowcaps cannot be put out');
run(['ne']);
has('n', 'not getting past', 'Grumbleback blocks the burrow');
has('give bread to mole', '', 'bread rule loads');
has('give honeycomb to mole', 'shuffles aside', 'give honeycomb to Grumbleback');
run(['n']);
has('take ingot', 'bronze ingot', 'bronze ingot from the den');
run(['s', 'sw', 'w']);
has('look', 'draining', 'gallery drains because the mill is turning');
run(['d']);
has('take key', 'bellwright key', 'bellwright key from the drained gallery');
run(['u', 'e', 's']);
has('pull lever', 'Great Hall', 'ride the lift back up');
check(room() === 'lift_top', 'at the lift top');
run(['nw', 'drop prybar']);
has('unlock door', 'Treasury', 'unlock the treasury with the bellwright key');
run(['n']);
has('look', 'Treasury of the Craft', 'inside the treasury');
run(['s', 'w']);
has('light furnace', 'needs coal', 'furnace without coal');
run(['n', 'take coal', 's']);
has('put coal in furnace', 'ready to light', 'coal in the furnace');
has('put ingot in mould', 'roaring first', 'cold mould refuses bronze');
has('light furnace', 'white-hot', 'light the furnace with the torch');
has('put ingot in mould', 'bronze clapper', 'cast the clapper');
has('i', 'bronze clapper', 'clapper in inventory');
run(['e', 'e']);
has('read tome', 'twice toward the rising sun', 'maze verse in the library');
has('read ledger', 'Bring coal', 'foundry ledger');

// ------------------------------------------------------------- Chapter 2: the caverns and the Heart
run(['w', 'se', 'pull lever', 'n', 'e']);
has('e', 'too thick', 'webs block the way');
has('burn web', 'shrivels', 'burn the webs');
run(['e']);
has('take key', 'brass key', 'brass key in the spider\'s larder');
run(['w', 'w', 'se']);
has('row boat', 'far landing', 'row the ferry across');
check(room() === 'river_landing', 'on the far landing');
run(['n', 'n']);
has('n', 'Echoing Passage', 'a wrong turn leads into a dead end');
has('w', 'Mouth of the Echoes', 'the dead end leads you home');
run(['n', 'e', 'e', 'n']);
has('w', 'Chamber of Whispers', 'through the maze');
has('x whispers', 'Low... high... middle', 'whispers clue');
run(['n']);
has('n', 'shut fast', 'bronze door is shut');
has('ring high bell', 'not the right song', 'wrong first bell resets');
has('ring low bell', 'BONNNG', 'low bell');
has('ring middle bell', 'Begin again', 'wrong second bell resets');
run(['ring low bell', 'ring high bell']);
has('ring middle bell', 'rolls aside', 'low, high, middle opens the door');
run(['n']);
has('ring bell', 'no clapper', 'Great Bell without a clapper');
has('put clapper in bell', 'voice back', 'hang the clapper');
has('ring great bell', 'Chapter 2 complete', 'ring the Great Bell: chapter 2 complete');
has('journal', 'woke the Great Bell', 'journal has chapter 2');
has('u', 'Top of the Hollow Hill', 'climb to the hilltop');
has('s', 'Old Road', 'sheep track home to the Old Road');

// ------------------------------------------------------------- Side checks
function place(string $room): void { global $pid; Db::run('UPDATE players SET room = ? WHERE id = ?', [$room, $pid]); }
function grant(string $kind): void { global $pid; Db::insert('INSERT INTO items (kind, player_id, lit) VALUES (?, ?, ?)', [$kind, $pid, $kind === 'glowcap' ? 1 : 0]); }
run(['drop all']);
grant('torch'); Db::run('UPDATE items SET lit = 1 WHERE player_id = ?', [$pid]);
grant('silver_bell'); grant('tuning_fork'); grant('rope');
place('bat_roost');
has('n', 'drive you back', 'bats block the grotto');
has('ring bell', 'flee', 'ring bell scatters the bats');
run(['n']);
has('read inscription', 'LOW, and then HIGH, and then MIDDLE', 'grotto inscription');
has('take crystal', 'star crystal', 'take the star crystal');
place('hilltop');
has('raise crystal', 'stars in broad daylight', 'raise the star crystal on the hilltop');
place('maze3');
has('strike fork', 'north', 'tuning fork hint in the maze');
place('maze5');
has('strike fork', 'nowhere', 'tuning fork in the dead end');
place('tower_base');
has('u', 'rotten', 'belfry needs a rope');
has('tie rope to beam', 'climb up', 'rope over the beam');
run(['u']);
has('read frame', 'deepest', 'belfry clue');
place('graveyard');
has('read grave', 'one note in between', 'graveyard clue');
place('barracks');
has('open footlocker', 'bar would open it', 'footlocker needs a prybar');

echo "\n$fails failure(s)\n";
exit($fails ? 1 : 0);
