<?php
declare(strict_types=1);

namespace App;

/**
 * Runs one typed command for one player against the shared world.
 * Every command runs inside a database transaction, so two players can never
 * pick up the same torch at the same moment.
 */
final class Engine
{
    public const DIRS = [
        'n' => 'north', 's' => 'south', 'e' => 'east', 'w' => 'west', 'u' => 'up', 'd' => 'down',
        'ne' => 'northeast', 'nw' => 'northwest', 'se' => 'southeast', 'sw' => 'southwest',
    ];
    private const OPPOSITE = [
        'n' => 's', 's' => 'n', 'e' => 'w', 'w' => 'e', 'u' => 'd', 'd' => 'u',
        'ne' => 'sw', 'sw' => 'ne', 'nw' => 'se', 'se' => 'nw',
    ];
    private const FROM_WORDS = [
        'n' => 'the north', 's' => 'the south', 'e' => 'the east', 'w' => 'the west', 'u' => 'above', 'd' => 'below',
        'ne' => 'the northeast', 'nw' => 'the northwest', 'se' => 'the southeast', 'sw' => 'the southwest',
    ];
    private const DIR_WORDS = [
        'n' => 'n', 'north' => 'n', 's' => 's', 'south' => 's', 'e' => 'e', 'east' => 'e', 'w' => 'w', 'west' => 'w',
        'u' => 'u', 'up' => 'u', 'upstairs' => 'u', 'd' => 'd', 'down' => 'd', 'downstairs' => 'd',
        'ne' => 'ne', 'northeast' => 'ne', 'nw' => 'nw', 'northwest' => 'nw',
        'se' => 'se', 'southeast' => 'se', 'sw' => 'sw', 'southwest' => 'sw',
    ];
    private const VERBS = [
        'look' => 'look', 'l' => 'look',
        'examine' => 'examine', 'x' => 'examine', 'inspect' => 'examine', 'check' => 'examine', 'describe' => 'examine', 'search' => 'examine',
        'read' => 'read',
        'go' => 'go', 'walk' => 'go', 'run' => 'go', 'head' => 'go', 'travel' => 'go', 'enter' => 'go',
        'take' => 'take', 'get' => 'take', 'grab' => 'take', 'pick' => 'take', 'collect' => 'take',
        'drop' => 'drop', 'discard' => 'drop',
        'inventory' => 'inventory', 'i' => 'inventory', 'inv' => 'inventory',
        'light' => 'light', 'ignite' => 'light', 'kindle' => 'light',
        'douse' => 'douse', 'extinguish' => 'douse', 'snuff' => 'douse',
        'give' => 'give', 'hand' => 'give', 'pass' => 'give',
        'say' => 'say', 'talk' => 'say',
        'who' => 'who',
        'help' => 'help', '?' => 'help', 'commands' => 'help',
        'journal' => 'journal', 'score' => 'journal', 'progress' => 'journal',
        'eat' => 'eat',
        'climb' => 'climb',
        'wait' => 'wait', 'z' => 'wait',
        'use' => 'use',
    ];
    private const PREPS = ['with', 'using', 'on', 'onto', 'to', 'into', 'in', 'inside', 'from', 'at', 'upon', 'over'];
    private const FILLER = ['the', 'a', 'an', 'my', 'some', 'of', 'that', 'this', 'those', 'these'];
    private const ONLINE_SECONDS = 600;

    private array $p;          // the acting player (id, name, room)
    private array $out = [];   // lines for the player: ['t' => type, 's' => text]

    public function __construct(array $player)
    {
        $this->p = $player;
    }

    /** Run a command; returns ['lines' => [...], 'room' => [...]]. */
    public function run(string $input): array
    {
        $input = trim(preg_replace('/\s+/', ' ', mb_substr($input, 0, 300)) ?? '');
        Db::run('UPDATE players SET last_seen = ? WHERE id = ?', [now(), $this->p['id']]);

        if ($input === '') {
            $this->describeRoom();
        } elseif ($input[0] === "'" || $input[0] === '"') {
            $this->say(trim(substr($input, 1), " \"'"));
        } else {
            $this->dispatch($input);
        }
        return ['lines' => $this->out, 'room' => $this->roomInfo()];
    }

    // =================================================================== parsing

    private function dispatch(string $input): void
    {
        $lower = mb_strtolower($input);
        $words = array_values(array_filter(explode(' ', preg_replace('/[^a-z0-9?\' -]/', '', $lower) ?? '')));
        if ($words === []) {
            $this->line('error', 'Say that again?');
            return;
        }
        $raw = $words[0];
        $rest = array_slice($words, 1);

        // A bare direction, or "go north".
        if (isset(self::DIR_WORDS[$raw]) && count($rest) === 0) {
            $this->go(self::DIR_WORDS[$raw]);
            return;
        }

        // Two-word verbs.
        if ($raw === 'pick' && ($rest[0] ?? '') === 'up') { array_shift($rest); }
        if ($raw === 'look' && in_array($rest[0] ?? '', ['at', 'in', 'into', 'under'], true)) { array_shift($rest); $raw = 'examine'; }
        if ($raw === 'put' && ($rest[0] ?? '') === 'down') { array_shift($rest); $raw = 'drop'; }
        if (in_array($raw, ['put', 'blow'], true) && ($rest[0] ?? '') === 'out') { array_shift($rest); $raw = 'douse'; }
        if ($raw === 'turn' && ($rest[0] ?? '') === 'in') { array_shift($rest); $raw = 'give'; }

        $verb = self::VERBS[$raw] ?? null;

        if ($verb === 'say') {
            $this->say(trim(mb_substr($input, mb_strlen($raw)), " \"'"));
            return;
        }

        // Split "dagger on rat" into the main object and the second object.
        $obj1 = [];
        $obj2 = [];
        $prep = null;
        foreach ($rest as $w) {
            if ($prep === null && $obj1 !== [] && in_array($w, self::PREPS, true)) {
                $prep = $w;
                continue;
            }
            if (in_array($w, self::FILLER, true)) {
                continue;
            }
            if ($prep === null) { $obj1[] = $w; } else { $obj2[] = $w; }
        }
        $o1 = implode(' ', $obj1);
        $o2 = implode(' ', $obj2);

        switch ($verb) {
            case 'look':      $o1 === '' ? $this->describeRoom() : $this->examine($o1); return;
            case 'examine':   $this->examine($o1); return;
            case 'read':      $this->read($o1); return;
            case 'go':        $this->goWord($o1); return;
            case 'climb':     $this->climb($o1); return;
            case 'take':      $this->take($o1); return;
            case 'drop':      $this->drop($o1); return;
            case 'inventory': $this->inventory(); return;
            case 'who':       $this->who(); return;
            case 'help':      $this->help(); return;
            case 'journal':   $this->journal(); return;
            case 'wait':      $this->line('text', 'Time passes. Somewhere, water drips.'); return;
            case 'eat':       if ($this->eat($o1)) { return; } break;
            case 'light':     if ($this->light($o1)) { return; } break;
            case 'douse':     $this->douse($o1); return;
            case 'give':      if ($o2 !== '' && $this->giveToPlayer($o1, $o2)) { return; } break;
            case 'use':       $this->use($o1, $o2); return;
        }

        if (!$this->applyRules($raw, $verb ?? $raw, $o1, $o2)) {
            $this->noRule($raw, $verb, $o1);
        }
    }

    // =================================================================== the room

    private function room(): array
    {
        return World::room($this->p['room']) ?? World::room(World::def()['start']);
    }

    /** Other players here and active in the last few minutes. */
    private function others(?string $roomKey = null): array
    {
        return Db::all('SELECT id, name FROM players WHERE room = ? AND id <> ? AND last_seen > ? ORDER BY name',
            [$roomKey ?? $this->p['room'], $this->p['id'], now() - self::ONLINE_SECONDS]);
    }

    private function isLit(?string $roomKey = null): bool
    {
        $roomKey ??= $this->p['room'];
        $room = World::room($roomKey);
        if (empty($room['dark'])) {
            return true;
        }
        $ids = array_map(fn($o) => (int) $o['id'], $this->others($roomKey));
        if ($roomKey === $this->p['room']) {
            $ids[] = (int) $this->p['id'];
        }
        $in = $ids === [] ? '0' : implode(',', $ids);
        return (int) Db::value("SELECT COUNT(*) FROM items WHERE lit = 1 AND (room = ? OR player_id IN ($in))", [$roomKey]) > 0;
    }

    private function held(): array
    {
        return Db::all('SELECT * FROM items WHERE player_id = ? ORDER BY id', [$this->p['id']]);
    }

    private function floor(): array
    {
        return Db::all('SELECT * FROM items WHERE room = ? ORDER BY id', [$this->p['room']]);
    }

    private function visibleThings(): array
    {
        if (!$this->isLit()) {
            return [];
        }
        return array_filter($this->room()['things'] ?? [], fn($t) => World::check($t['if'] ?? null));
    }

    private function describeRoom(): void
    {
        $room = $this->room();
        World::restock($this->p['room']);
        if (Db::value('SELECT 1 FROM visits WHERE player_id = ? AND room = ?', [$this->p['id'], $this->p['room']]) === null) {
            Db::run('INSERT INTO visits (player_id, room) VALUES (?, ?)', [$this->p['id'], $this->p['room']]);
        }

        $this->line('title', $room['name']);
        if (!$this->isLit()) {
            $this->line('text', 'It is pitch dark. You cannot see a thing, but you hear something skittering nearby. You need a light.');
            $this->listPlayers();
            return;
        }
        $text = $room['desc'];
        foreach ($room['details'] ?? [] as $d) {
            if (World::check($d['if'] ?? null)) {
                $text .= ' ' . $d['text'];
            }
        }
        $this->line('text', $text);

        $items = $this->floor();
        if ($items !== []) {
            $this->line('list', 'You see ' . self::listing(array_map(fn($i) => self::label($i), $items)) . '.');
        }
        $this->listPlayers();
        $exits = array_map(fn($d) => self::DIRS[$d], array_keys($room['exits'] ?? []));
        $this->line('dim', 'Exits: ' . ($exits ? implode(', ', $exits) : 'none') . '.');
    }

    private function listPlayers(): void
    {
        foreach ($this->others() as $o) {
            $lit = Db::value("SELECT COUNT(*) FROM items WHERE player_id = ? AND lit = 1", [$o['id']]);
            $this->line('list', $o['name'] . ' is here' . ($lit ? ', carrying a light' : '') . '.');
        }
    }

    /** Info the web page uses for its buttons. */
    private function roomInfo(): array
    {
        $room = $this->room();
        $lit = $this->isLit();
        return [
            'name'  => $room['name'],
            'exits' => array_values(array_map(fn($d) => self::DIRS[$d], array_keys($room['exits'] ?? []))),
            'items' => $lit ? array_values(array_unique(array_map(fn($i) => World::item($i['kind'])['nouns'][0], $this->floor()))) : [],
            'dark'  => !$lit,
            'last'  => (int) Db::value('SELECT COALESCE(MAX(id), 0) FROM events'),
        ];
    }

    // =================================================================== movement

    private function goWord(string $o): void
    {
        $w = explode(' ', $o)[0] ?? '';
        if (isset(self::DIR_WORDS[$w])) {
            $this->go(self::DIR_WORDS[$w]);
        } else {
            $this->line('error', 'Which way? Try north, south, east, west, up or down.');
        }
    }

    private function climb(string $o): void
    {
        if (in_array($o, ['', 'down', 'well', 'into well', 'rope down'], true) && isset($this->room()['exits']['d'])) {
            $this->go('d');
        } elseif (in_array($o, ['', 'up', 'rope', 'out', 'stairs', 'steps'], true) && isset($this->room()['exits']['u'])) {
            $this->go('u');
        } elseif ($o === 'down' || $o === 'well') {
            $this->go('d');
        } else {
            $this->line('error', 'There is nothing here to climb.');
        }
    }

    private function go(string $dir): void
    {
        $room = $this->room();
        $exit = $room['exits'][$dir] ?? null;
        if ($exit === null) {
            $this->line('error', 'You cannot go that way.');
            return;
        }
        $to = is_array($exit) ? $exit['to'] : $exit;
        if (is_array($exit) && !World::check($exit['if'] ?? null)) {
            $this->line('error', $exit['fail'] ?? 'Something blocks the way.');
            return;
        }
        if (!$this->isLit() && !empty(World::room($to)['dark']) && !$this->carriesLight()) {
            $this->line('error', 'You grope forward, but in this blackness you could walk into anything. You had better head back toward the light, or find a torch.');
            return;
        }
        $from = $this->p['room'];
        $this->event($from, $this->p['name'] . ' leaves ' . self::DIRS[$dir] . '.');
        Db::run('UPDATE players SET room = ? WHERE id = ?', [$to, $this->p['id']]);
        $this->p['room'] = $to;
        $this->event($to, $this->p['name'] . ' arrives from ' . self::FROM_WORDS[self::OPPOSITE[$dir]] . '.');
        $this->describeRoom();
    }

    private function carriesLight(): bool
    {
        return (int) Db::value('SELECT COUNT(*) FROM items WHERE player_id = ? AND lit = 1', [$this->p['id']]) > 0;
    }

    // =================================================================== objects

    /** Things, held items, floor items and players matching a phrase like "iron key". */
    private function resolve(string $phrase): array
    {
        $r = ['things' => [], 'held' => [], 'floor' => [], 'players' => []];
        if ($phrase === '') {
            return $r;
        }
        $words = explode(' ', $phrase);
        $head = end($words);
        $matches = function (array $nouns, string $name) use ($phrase, $head, $words): bool {
            return in_array($head, $nouns, true) || $phrase === mb_strtolower($name)
                || count(array_intersect($words, $nouns)) > 0;
        };
        foreach ($this->visibleThings() as $key => $t) {
            if ($matches($t['nouns'], $key)) {
                $r['things'][] = $key;
            }
        }
        foreach ($this->held() as $i) {
            $def = World::item($i['kind']);
            if ($def && $matches($def['nouns'], $def['name'])) {
                $r['held'][] = $i;
            }
        }
        if ($this->isLit()) {
            foreach ($this->floor() as $i) {
                $def = World::item($i['kind']);
                if ($def && $matches($def['nouns'], $def['name'])) {
                    $r['floor'][] = $i;
                }
            }
        }
        foreach ($this->others() as $o) {
            if (mb_strtolower($o['name']) === $phrase || mb_strtolower($o['name']) === $head) {
                $r['players'][] = $o;
            }
        }
        return $r;
    }

    private function examine(string $o): void
    {
        if ($o === '') {
            $this->describeRoom();
            return;
        }
        if (in_array($o, ['me', 'myself', 'self'], true)) {
            $this->inventory();
            return;
        }
        $r = $this->resolve($o);
        if ($r['things']) {
            $this->line('text', $this->room()['things'][$r['things'][0]]['desc']);
        } elseif ($r['held'] || $r['floor']) {
            $i = $r['held'][0] ?? $r['floor'][0];
            $def = World::item($i['kind']);
            $this->line('text', $def['desc'] . ($i['lit'] ? ' ' . ($def['lit_desc'] ?? 'It is burning.') : ''));
        } elseif ($r['players']) {
            $pl = $r['players'][0];
            $items = Db::all('SELECT * FROM items WHERE player_id = ? ORDER BY id', [$pl['id']]);
            $this->line('text', $pl['name'] . ($items ? ' is carrying ' . self::listing(array_map(fn($i) => self::label($i), $items)) . '.' : ' is empty-handed.'));
        } else {
            $this->line('error', $this->isLit() ? "You don't see any $o here." : 'It is too dark to see.');
        }
    }

    private function read(string $o): void
    {
        $r = $this->resolve($o);
        if ($r['things'] && isset($this->room()['things'][$r['things'][0]]['read'])) {
            foreach (explode("\n", $this->room()['things'][$r['things'][0]]['read']) as $l) {
                $this->line('read', $l);
            }
        } elseif ($o === '') {
            $this->line('error', 'Read what?');
        } else {
            $this->examine($o);
        }
    }

    private function take(string $o): void
    {
        if ($o === '') {
            $this->line('error', 'Take what?');
            return;
        }
        if (!$this->isLit()) {
            $this->line('error', 'You pat around in the dark and find nothing but dirt. You need a light.');
            return;
        }
        $limit = (int) World::def()['carry_limit'];
        if ($o === 'all' || $o === 'everything') {
            $items = $this->floor();
            if ($items === []) {
                $this->line('error', 'There is nothing here to take.');
                return;
            }
        } else {
            $r = $this->resolve($o);
            if ($r['floor']) {
                $items = [$r['floor'][0]];
            } elseif ($r['held']) {
                $this->line('error', 'You already have that.');
                return;
            } elseif ($r['things']) {
                $this->line('error', 'That is not something you can carry.');
                return;
            } elseif ($r['players']) {
                $this->line('error', $r['players'][0]['name'] . ' would rather you didn\'t.');
                return;
            } else {
                $this->line('error', "You don't see any $o here.");
                return;
            }
        }
        foreach ($items as $i) {
            $count = (int) Db::value('SELECT COUNT(*) FROM items WHERE player_id = ?', [$this->p['id']]);
            if ($count >= $limit) {
                $this->line('error', "Your hands are full: you can carry $limit things. Drop something first.");
                break;
            }
            $locked = Db::one('SELECT * FROM items WHERE id = ? AND room = ?' . Db::lock(), [$i['id'], $this->p['room']]);
            if ($locked === null) {
                $this->line('error', 'Someone else got to it first.');
                continue;
            }
            Db::run('UPDATE items SET player_id = ?, room = NULL, dropped_at = NULL WHERE id = ?', [$this->p['id'], $i['id']]);
            $name = World::item($i['kind'])['name'];
            $this->line('good', 'You take the ' . $name . '.');
            $this->event(null, $this->p['name'] . ' picks up ' . self::label($i) . '.');
        }
        World::restock($this->p['room']);
    }

    private function drop(string $o): void
    {
        $items = ($o === 'all' || $o === 'everything') ? $this->held() : array_slice($this->resolve($o)['held'], 0, 1);
        if ($o === '') {
            $this->line('error', 'Drop what?');
            return;
        }
        if ($items === []) {
            $this->line('error', "You aren't carrying that.");
            return;
        }
        $wasLit = $this->isLit();
        foreach ($items as $i) {
            Db::run('UPDATE items SET player_id = NULL, room = ?, dropped_at = ? WHERE id = ?', [$this->p['room'], now(), $i['id']]);
            $this->line('text', 'You drop the ' . World::item($i['kind'])['name'] . '.');
            $this->event(null, $this->p['name'] . ' drops ' . self::label($i) . '.');
        }
        if (!$wasLit && $this->isLit()) {
            $this->line('good', 'The torchlight on the ground lights up the whole place.');
        }
    }

    private function inventory(): void
    {
        $items = $this->held();
        $limit = (int) World::def()['carry_limit'];
        if ($items === []) {
            $this->line('text', "You are empty-handed. (You can carry up to $limit things.)");
            return;
        }
        $this->line('text', 'You are carrying ' . self::listing(array_map(fn($i) => self::label($i), $items))
            . '. (' . count($items) . " of $limit)");
    }

    private function eat(string $o): bool
    {
        foreach ($this->resolve($o)['held'] as $i) {
            $def = World::item($i['kind']);
            if (isset($def['eat'])) {
                Db::run('DELETE FROM items WHERE id = ?', [$i['id']]);
                $this->line('text', $def['eat']);
                $this->event(null, $this->p['name'] . ' eats ' . self::label($i) . '.');
                return true;
            }
        }
        if ($this->resolve($o)['floor']) {
            $this->line('error', 'Pick it up first.');
            return true;
        }
        return false;
    }

    // =================================================================== light

    /** Returns false to let the rules handle it (e.g. "light brambles with torch"). */
    private function light(string $o): bool
    {
        $r = $this->resolve($o === '' ? 'torch' : $o);
        $target = null;
        foreach ($r['held'] as $i) {
            if (!empty(World::item($i['kind'])['lightable'])) {
                if (!$i['lit']) { $target = $i; break; }
                $target ??= $i;
            }
        }
        if ($target === null) {
            if ($r['things'] || $o === '') {
                return false; // e.g. "light brambles": let the rules decide
            }
            if ($r['floor']) {
                $this->line('error', 'Pick it up first.');
                return true;
            }
            return false;
        }
        if ($target['lit']) {
            $this->line('text', 'It is already burning.');
            return true;
        }

        $source = null;
        $flames = self::flameKinds();
        if (!empty($this->room()['fire'])) {
            $source = 'You hold the torch to the forge. It catches with a soft whump and burns bright.';
        } elseif ((int) Db::value("SELECT COUNT(*) FROM items WHERE player_id = ? AND lit = 1 AND kind IN ($flames)", [$this->p['id']]) > 0) {
            $source = 'You light it from the flame you are already carrying.';
        } elseif ((int) Db::value("SELECT COUNT(*) FROM items WHERE room = ? AND lit = 1 AND kind IN ($flames)", [$this->p['room']]) > 0) {
            $source = 'You light it from the burning torch on the ground.';
        } else {
            foreach ($this->others() as $o2) {
                if ((int) Db::value("SELECT COUNT(*) FROM items WHERE player_id = ? AND lit = 1 AND kind IN ($flames)", [$o2['id']]) > 0) {
                    $source = 'You touch your torch to ' . $o2['name'] . "'s flame. It catches.";
                    break;
                }
            }
        }
        if ($source === null) {
            $this->line('error', 'You have nothing to light it with. The forge in the smithy would do, or anyone else\'s flame.');
            return true;
        }
        $wasLit = $this->isLit();
        Db::run('UPDATE items SET lit = 1 WHERE id = ?', [$target['id']]);
        $this->line('good', $source);
        $this->event(null, $this->p['name'] . ' lights a torch.');
        if (!$wasLit) {
            $this->line('text', 'Light flares across the walls.');
            $this->describeRoom();
        }
        return true;
    }

    private function douse(string $o): void
    {
        foreach ($this->resolve($o === '' ? 'torch' : $o)['held'] as $i) {
            if ($i['lit'] && !empty(World::item($i['kind'])['glows'])) {
                $this->line('error', 'It glows all by itself. There is no putting it out.');
                return;
            }
            if ($i['lit']) {
                Db::run('UPDATE items SET lit = 0 WHERE id = ?', [$i['id']]);
                $this->line('text', 'You smother the flame. Smoke curls up from the torch.');
                $this->event(null, $this->p['name'] . ' puts out a torch.');
                return;
            }
        }
        $this->line('error', 'You are not carrying anything that is burning.');
    }

    // =================================================================== people

    private function giveToPlayer(string $o1, string $o2): bool
    {
        $target = $this->resolve($o2)['players'][0] ?? null;
        if ($target === null) {
            return false; // not a player: maybe a rule ("give apple to rat")
        }
        $item = $this->resolve($o1)['held'][0] ?? null;
        if ($item === null) {
            $this->line('error', "You aren't carrying that.");
            return true;
        }
        $limit = (int) World::def()['carry_limit'];
        if ((int) Db::value('SELECT COUNT(*) FROM items WHERE player_id = ?', [$target['id']]) >= $limit) {
            $this->line('error', $target['name'] . ' has their hands full.');
            return true;
        }
        Db::run('UPDATE items SET player_id = ? WHERE id = ?', [$target['id'], $item['id']]);
        $label = self::label($item);
        $this->line('good', 'You give ' . $target['name'] . ' ' . $label . '.');
        $this->event(null, $this->p['name'] . ' gives you ' . $label . '.', (int) $target['id']);
        foreach ($this->others() as $o) {
            if ((int) $o['id'] !== (int) $target['id']) {
                $this->event(null, $this->p['name'] . ' gives ' . $target['name'] . ' ' . $label . '.', (int) $o['id']);
            }
        }
        return true;
    }

    private function say(string $text): void
    {
        $text = trim($text);
        if ($text === '') {
            $this->line('error', 'Say what?');
            return;
        }
        if (!RateLimit::hit('say:' . $this->p['id'], 20, 60)) {
            $this->line('error', 'Catch your breath for a moment.');
            return;
        }
        $text = mb_substr($text, 0, 200);
        $this->line('say', 'You say, "' . $text . '"');
        $this->event(null, $this->p['name'] . ' says, "' . $text . '"', null, 'say');
    }

    private function who(): void
    {
        $rows = Db::all('SELECT name, room FROM players WHERE last_seen > ? ORDER BY name', [now() - self::ONLINE_SECONDS]);
        $this->line('text', count($rows) === 1 ? 'Only you are out exploring right now.' : count($rows) . ' explorers are about:');
        if (count($rows) > 1) {
            foreach ($rows as $r) {
                $this->line('list', $r['name'] . ' — ' . (World::room($r['room'])['name'] ?? 'somewhere'));
            }
        }
    }

    private function journal(): void
    {
        $seen = (int) Db::value('SELECT COUNT(*) FROM visits WHERE player_id = ?', [$this->p['id']]);
        $total = count(World::def()['rooms']);
        $this->line('title', 'Your journal');
        $this->line('text', "Places discovered: $seen of $total.");
        $entries = Db::all('SELECT entry FROM journal WHERE player_id = ? ORDER BY created_at', [$this->p['id']]);
        if ($entries === []) {
            $this->line('dim', 'No deeds recorded yet.');
        }
        foreach ($entries as $e) {
            $this->line('good', '★ ' . $e['entry']);
        }
    }

    private function help(): void
    {
        $this->line('title', 'How to play');
        foreach ([
            'Type what you want to do, in plain words. A few examples:',
            '  LOOK (L) · EXAMINE WELL (X WELL) · READ BOARD',
            '  NORTH or N, SOUTH, EAST, WEST, UP, DOWN',
            '  TAKE TORCH · DROP TORCH · INVENTORY (I) · TAKE ALL',
            '  LIGHT TORCH · KILL RAT WITH DAGGER · UNLOCK DOOR WITH KEY',
            '  USE SICKLE ON BRAMBLES · PUT MOONSTONE IN HOLLOW',
            'Other explorers share this world. What you open stays open for them, for a while.',
            '  SAY hello (or \'hello) · GIVE TORCH TO MARA · EXAMINE MARA · WHO',
            '  Some things need two people at once.',
            'JOURNAL shows your discoveries. You can carry ' . World::def()['carry_limit'] . ' things. Nothing here can kill you.',
        ] as $l) {
            $this->line('text', $l);
        }
    }

    // =================================================================== rules

    private function use(string $o1, string $o2): void
    {
        if ($o1 === '') {
            $this->line('error', 'Use what?');
            return;
        }
        if ($o2 === '') {
            $this->line('error', 'Use it on what?');
            return;
        }
        // "use X on Y" means "do whatever X does to Y", whatever the verb.
        if ($this->applyRules(null, null, $o2, $o1) || $this->applyRules(null, null, $o1, $o2)) {
            return;
        }
        $this->noRule('use', 'use', $o1);
    }

    /** Keys a phrase can refer to: visible thing keys and held item kinds. */
    private function keys(string $phrase): array
    {
        $r = $this->resolve($phrase);
        return array_values(array_unique(array_merge($r['things'], array_map(fn($i) => $i['kind'], $r['held']))));
    }

    /** Try the world's rules. $raw/$verb null = any verb (for "use"). Returns true if one ran. */
    private function applyRules(?string $raw, ?string $verb, string $o1, string $o2): bool
    {
        if ($o1 === '') {
            return false;
        }
        $k1 = $this->keys($o1);
        $k2 = $o2 === '' ? [] : $this->keys($o2);
        $heldKinds = array_map(fn($i) => $i['kind'], $this->held());
        $things = array_keys($this->visibleThings());

        foreach (World::def()['rules'] as $idx => $rule) {
            if ($raw !== null && !in_array($raw, $rule['verbs'], true) && !in_array($verb, $rule['verbs'], true)) {
                continue;
            }
            if ($raw === null && empty($rule['with'])) {
                continue; // "use" needs a two-object rule
            }
            if (isset($rule['room']) && $rule['room'] !== $this->p['room']) {
                continue;
            }
            if (!in_array($rule['target'], $k1, true)) {
                continue;
            }
            $auto = null;
            if (!empty($rule['with'])) {
                $with = $rule['with'];
                if ($o2 !== '') {
                    if (!in_array($with, $k2, true)) {
                        continue;
                    }
                } elseif (in_array($with, $heldKinds, true)) {
                    $auto = World::item($with)['name'];
                } elseif (in_array($with, $things, true)) {
                    // "tie rope" at the well: the well is right there
                } else {
                    continue;
                }
                if (!empty($rule['lit']) && (int) Db::value('SELECT COUNT(*) FROM items WHERE player_id = ? AND kind = ? AND lit = 1',
                        [$this->p['id'], $with]) === 0) {
                    continue;
                }
            }
            if (!World::check($rule['if'] ?? null)) {
                continue;
            }

            if ($auto !== null) {
                $this->line('dim', "(with the $auto)");
            }
            if (!empty($rule['coop']) && !$this->coopReady($idx, $rule)) {
                return true;
            }
            $this->effects($rule);
            return true;
        }
        return false;
    }

    /** Puzzles that need several people acting within a short window. */
    private function coopReady(int $idx, array $rule): bool
    {
        $window = (int) ($rule['window'] ?? 30);
        $prefix = "coop:$idx:";
        World::set($prefix . $this->p['id'], $window);
        $others = array_map(fn($o) => $prefix . $o['id'], $this->others());
        $ready = 1;
        foreach ($others as $k) {
            if (World::isOn($k)) {
                $ready++;
            }
        }
        if ($ready < (int) $rule['coop']) {
            $this->line('text', $rule['waiting'] ?? 'It will not budge on your own. You need help.');
            if (!empty($rule['waiting_others'])) {
                $this->event(null, str_replace('{name}', $this->p['name'], $rule['waiting_others']));
            }
            return false;
        }
        Db::run('DELETE FROM world_state WHERE k LIKE ?', [$prefix . '%']);
        return true;
    }

    private function effects(array $rule): void
    {
        foreach ($rule['set'] ?? [] as $k => $secs) {
            World::set($k, (int) $secs);
        }
        foreach ($rule['unset'] ?? [] as $k) {
            World::unset($k);
        }
        if (!empty($rule['consume'])) {
            $kind = $rule[$rule['consume']];
            $id = Db::value('SELECT id FROM items WHERE player_id = ? AND kind = ? ORDER BY lit, id LIMIT 1', [$this->p['id'], $kind]);
            if ($id !== null) {
                Db::run('DELETE FROM items WHERE id = ?', [$id]);
            }
        }
        if (!empty($rule['journal'])) {
            $ids = array_merge([(int) $this->p['id']], array_map(fn($o) => (int) $o['id'], $this->others()));
            foreach ($ids as $pid) {
                if (Db::value('SELECT 1 FROM journal WHERE player_id = ? AND entry = ?', [$pid, $rule['journal']]) === null) {
                    Db::run('INSERT INTO journal (player_id, entry, created_at) VALUES (?, ?, ?)', [$pid, $rule['journal'], now()]);
                }
            }
        }
        $good = !empty($rule['set']) || !empty($rule['journal']) || !empty($rule['give']) || !empty($rule['move']);
        foreach (explode("\n", $rule['say']) as $l) {
            $this->line($good ? 'good' : 'text', $l);
        }
        if (!empty($rule['give'])) {
            $this->giveItem($rule['give']);
        }
        if (!empty($rule['others'])) {
            $this->event(null, str_replace('{name}', $this->p['name'], $rule['others']));
        }
        if (!empty($rule['move'])) {
            $to = $rule['move'];
            Db::run('UPDATE players SET room = ? WHERE id = ?', [$to, $this->p['id']]);
            $this->p['room'] = $to;
            $this->event($to, str_replace('{name}', $this->p['name'], $rule['arrive'] ?? '{name} arrives.'));
            $this->describeRoom();
        }
    }

    /** A rule hands the player a new item (into their hands, or at their feet if full). */
    private function giveItem(string $kind): void
    {
        $def = World::item($kind);
        $limit = (int) World::def()['carry_limit'];
        $count = (int) Db::value('SELECT COUNT(*) FROM items WHERE player_id = ?', [$this->p['id']]);
        $lit = !empty($def['glows']) ? 1 : 0;
        if ($count < $limit) {
            Db::insert('INSERT INTO items (kind, room, player_id, lit, home, dropped_at) VALUES (?, NULL, ?, ?, NULL, NULL)',
                [$kind, $this->p['id'], $lit]);
            $this->line('dim', '(You now have the ' . $def['name'] . '.)');
        } else {
            Db::insert('INSERT INTO items (kind, room, player_id, lit, home, dropped_at) VALUES (?, ?, NULL, ?, NULL, ?)',
                [$kind, $this->p['room'], $lit, now()]);
            $this->line('dim', '(Your hands are full, so the ' . $def['name'] . ' lands at your feet.)');
        }
    }

    /** Item kinds that are real flames (a torch can be lit from them). */
    private static function flameKinds(): string
    {
        $kinds = [];
        foreach (World::def()['items'] as $k => $d) {
            if (!empty($d['lightable'])) {
                $kinds[] = Db::pdo()->quote($k);
            }
        }
        return $kinds ? implode(',', $kinds) : "''";
    }

    private function noRule(string $raw, ?string $verb, string $o1): void
    {
        if ($verb === null && !$this->isRuleVerb($raw)) {
            $this->line('error', "I don't know how to \"$raw\". Type HELP for some ideas.");
            return;
        }
        if ($o1 === '') {
            $this->line('error', ucfirst($raw) . ' what?');
            return;
        }
        $r = $this->resolve($o1);
        if (!$r['things'] && !$r['held'] && !$r['floor'] && !$r['players']) {
            $this->line('error', $this->isLit() ? "You don't see any $o1 here." : 'It is too dark to see.');
        } elseif ($r['floor'] && !$r['held']) {
            $this->line('error', 'You would need to pick it up first.');
        } elseif ($r['players']) {
            $this->line('error', $r['players'][0]['name'] . ' gives you a puzzled look.');
        } else {
            $this->line('error', 'Nothing useful happens.');
        }
    }

    private function isRuleVerb(string $w): bool
    {
        foreach (World::def()['rules'] as $r) {
            if (in_array($w, $r['verbs'], true)) {
                return true;
            }
        }
        return false;
    }

    // =================================================================== output

    private function line(string $type, string $text): void
    {
        $this->out[] = ['t' => $type, 's' => $text];
    }

    /** Something other players see: everyone in $room (default: here), or one player. */
    private function event(?string $room, string $text, ?int $target = null, string $type = 'event'): void
    {
        Db::run('INSERT INTO events (room, actor_id, target_id, kind, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
            [$room ?? $this->p['room'], $this->p['id'], $target, $type, $text, now()]);
    }

    public static function label(array $item): string
    {
        $name = World::item($item['kind'])['name'];
        $article = preg_match('/^[aeiou]/i', $name) ? 'an' : 'a';
        $state = !empty(World::item($item['kind'])['glows']) ? ' (glowing)' : ' (burning)';
        return "$article $name" . ($item['lit'] ? $state : '');
    }

    public static function listing(array $parts): string
    {
        if (count($parts) <= 1) {
            return implode('', $parts);
        }
        $last = array_pop($parts);
        return implode(', ', $parts) . ' and ' . $last;
    }

    /** New things other players did that this player can see. */
    public static function poll(array $player, int $since): array
    {
        $rows = Db::all(
            'SELECT id, kind, body FROM events
             WHERE id > ? AND actor_id <> ? AND ((room = ? AND target_id IS NULL) OR target_id = ?)
             ORDER BY id LIMIT 50',
            [$since, $player['id'], $player['room'], $player['id']]
        );
        return [
            'lines' => array_map(fn($r) => ['t' => $r['kind'] === 'say' ? 'say' : 'event', 's' => $r['body']], $rows),
            'last'  => (int) Db::value('SELECT COALESCE(MAX(id), 0) FROM events'),
        ];
    }
}
