<?php
declare(strict_types=1);

namespace App;

/** The world definition (world/*.php) plus the shared switches and item spawns stored in the database. */
final class World
{
    private static ?array $def = null;

    public static function def(): array
    {
        if (self::$def === null) {
            $file = APP_ROOT . '/world/' . (config('world') ?: 'hollow_hill') . '.php';
            self::$def = require $file;
        }
        return self::$def;
    }

    public static function room(string $key): ?array
    {
        return self::def()['rooms'][$key] ?? null;
    }

    public static function item(string $kind): ?array
    {
        return self::def()['items'][$kind] ?? null;
    }

    // ------------------------------------------------------------ shared switches

    public static function isOn(string $key): bool
    {
        $until = Db::value('SELECT until_at FROM world_state WHERE k = ?', [$key]);
        return $until !== null && ((int) $until === 0 || (int) $until > now());
    }

    /** 'switch' or '!switch'; a list must all hold. */
    public static function check(string|array|null $cond): bool
    {
        if ($cond === null || $cond === '' || $cond === []) {
            return true;
        }
        foreach ((array) $cond as $c) {
            $neg = str_starts_with($c, '!');
            $on = self::isOn(ltrim($c, '!'));
            if ($neg === $on) {
                return false;
            }
        }
        return true;
    }

    public static function set(string $key, int $seconds): void
    {
        $until = $seconds === 0 ? 0 : now() + $seconds;
        Db::run('DELETE FROM world_state WHERE k = ?', [$key]);
        Db::run('INSERT INTO world_state (k, until_at) VALUES (?, ?)', [$key, $until]);
    }

    public static function unset(string $key): void
    {
        Db::run('DELETE FROM world_state WHERE k = ?', [$key]);
    }

    // ------------------------------------------------------------ spawns

    /** Keep each room's spawn items stocked: if one is missing, replace it after its delay. */
    public static function restock(string $roomKey): void
    {
        $room = self::room($roomKey);
        foreach ($room['spawns'] ?? [] as $kind => $delay) {
            $k = $roomKey . ':' . $kind;
            $have = (int) Db::value('SELECT COUNT(*) FROM items WHERE room = ? AND kind = ?', [$roomKey, $kind]);
            if ($have > 0) {
                Db::run('DELETE FROM spawn_timers WHERE k = ?', [$k]);
                continue;
            }
            $since = Db::value('SELECT missing_since FROM spawn_timers WHERE k = ?', [$k]);
            if ($since === null) {
                Db::run('INSERT INTO spawn_timers (k, missing_since) VALUES (?, ?)', [$k, now()]);
            } elseif (now() - (int) $since >= (int) $delay) {
                self::spawn($kind, $roomKey);
                Db::run('DELETE FROM spawn_timers WHERE k = ?', [$k]);
            }
        }
    }

    public static function spawn(string $kind, string $roomKey): int
    {
        $lit = !empty(self::item($kind)['glows']) ? 1 : 0;
        return Db::insert('INSERT INTO items (kind, room, player_id, lit, home, dropped_at) VALUES (?, ?, NULL, ?, ?, NULL)',
            [$kind, $roomKey, $lit, $roomKey]);
    }

    /** Place every spawn item that is not in its room yet. Used by bin/migrate.php. */
    public static function seed(): int
    {
        $n = 0;
        foreach (self::def()['rooms'] as $roomKey => $room) {
            foreach ($room['spawns'] ?? [] as $kind => $_) {
                if ((int) Db::value('SELECT COUNT(*) FROM items WHERE room = ? AND kind = ?', [$roomKey, $kind]) === 0) {
                    self::spawn($kind, $roomKey);
                    $n++;
                }
            }
        }
        return $n;
    }

    private static function thingExists(string $key): bool
    {
        foreach (self::def()['rooms'] as $room) {
            if (isset($room['things'][$key])) {
                return true;
            }
        }
        return false;
    }

    /** Sanity-check the world file; returns a list of problems. */
    public static function validate(): array
    {
        $d = self::def();
        $errors = [];
        if (!isset($d['rooms'][$d['start'] ?? ''])) {
            $errors[] = "start room '{$d['start']}' does not exist";
        }
        foreach ($d['rooms'] as $key => $room) {
            foreach ($room['exits'] ?? [] as $dir => $exit) {
                $to = is_array($exit) ? $exit['to'] : $exit;
                if (!isset($d['rooms'][$to])) {
                    $errors[] = "$key: exit $dir goes to unknown room '$to'";
                }
                if (!isset(Engine::DIRS[$dir])) {
                    $errors[] = "$key: unknown direction '$dir'";
                }
            }
            foreach ($room['spawns'] ?? [] as $kind => $_) {
                if (!isset($d['items'][$kind])) {
                    $errors[] = "$key: spawns unknown item '$kind'";
                }
            }
        }
        foreach ($d['rules'] as $i => $r) {
            foreach (['room'] as $f) {
                if (isset($r[$f]) && !isset($d['rooms'][$r[$f]])) {
                    $errors[] = "rule #$i: unknown room '{$r[$f]}'";
                }
            }
            if (isset($r['move']) && !isset($d['rooms'][$r['move']])) {
                $errors[] = "rule #$i: moves to unknown room '{$r['move']}'";
            }
            if (isset($r['give']) && !isset($d['items'][$r['give']])) {
                $errors[] = "rule #$i: gives unknown item '{$r['give']}'";
            }
            if (isset($r['with']) && !isset($d['items'][$r['with']]) && !self::thingExists($r['with'])) {
                $errors[] = "rule #$i: 'with' names unknown item or thing '{$r['with']}'";
            }
            if (!isset($d['items'][$r['target'] ?? '']) && !self::thingExists($r['target'] ?? '')) {
                $errors[] = "rule #$i: target names unknown item or thing '" . ($r['target'] ?? '') . "'";
            }
            if (empty($r['verbs']) || empty($r['target']) || empty($r['say'])) {
                $errors[] = "rule #$i: needs verbs, target and say";
            }
        }
        return $errors;
    }
}
