<?php
declare(strict_types=1);

require_once __DIR__ . '/Engine.php';
require_once __DIR__ . '/I18n.php';

final class Store
{
    private PDO $pdo;
    private int $txDepth = 0;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->migrate();
    }

    public static function open(?string $dir = null): self
    {
        $dir = $dir ?? dataDir();
        if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
            throw new RuntimeException('De datamap moet schrijfbaar zijn.');
        }
        $path = $dir . '/allianties.sqlite';
        $pdo = new PDO('sqlite:' . $path, null, null, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        $pdo->exec('PRAGMA journal_mode = WAL');
        $pdo->exec('PRAGMA foreign_keys = ON');
        $pdo->exec('PRAGMA busy_timeout = 4000');
        return new self($pdo);
    }

    private function migrate(): void
    {
        $this->pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS games (
    id TEXT PRIMARY KEY,
    code TEXT UNIQUE NOT NULL,
    host_id TEXT NOT NULL,
    status TEXT NOT NULL,
    payload TEXT NOT NULL,
    updated INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS games_status ON games (status);
CREATE TABLE IF NOT EXISTS members (
    game_id TEXT NOT NULL,
    user_id TEXT NOT NULL,
    PRIMARY KEY (game_id, user_id)
);
CREATE INDEX IF NOT EXISTS members_user ON members (user_id);
CREATE TABLE IF NOT EXISTS profiles (
    user_id TEXT PRIMARY KEY,
    locale TEXT,
    avatar TEXT,
    name TEXT,
    updated INTEGER NOT NULL
);
SQL);
    }

    /** @template T @param callable():T $fn @return T */
    public function tx(callable $fn): mixed
    {
        if ($this->txDepth === 0) {
            $this->pdo->exec('BEGIN IMMEDIATE');
        }
        $this->txDepth++;
        try {
            $result = $fn();
            $this->txDepth--;
            if ($this->txDepth === 0) {
                $this->pdo->exec('COMMIT');
            }
            return $result;
        } catch (Throwable $e) {
            if ($this->txDepth > 0) {
                $this->txDepth = 0;
                try {
                    $this->pdo->exec('ROLLBACK');
                } catch (Throwable $ignored) {
                }
            }
            throw $e;
        }
    }

    public function now(): int
    {
        return Engine::now();
    }

    private function save(array $game): void
    {
        $now = $this->now();
        $stmt = $this->pdo->prepare(
            'INSERT INTO games (id, code, host_id, status, payload, updated)
             VALUES (:id, :code, :host, :status, :payload, :updated)
             ON CONFLICT(id) DO UPDATE SET
                code = excluded.code,
                host_id = excluded.host_id,
                status = excluded.status,
                payload = excluded.payload,
                updated = excluded.updated'
        );
        $stmt->execute([
            ':id' => $game['id'],
            ':code' => $game['code'],
            ':host' => $game['host_id'],
            ':status' => $game['status'],
            ':payload' => json_encode($game, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            ':updated' => $now,
        ]);
        $this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$game['id']]);
        $ins = $this->pdo->prepare('INSERT INTO members (game_id, user_id) VALUES (?, ?)');
        foreach ($game['players'] as $p) {
            $ins->execute([$game['id'], $p['id']]);
        }
    }

    private function deleteGame(string $id): void
    {
        $this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$id]);
        $this->pdo->prepare('DELETE FROM games WHERE id = ?')->execute([$id]);
    }

    public function load(string $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        if (!$row) {
            return null;
        }
        $game = json_decode((string) $row['payload'], true);
        return is_array($game) ? $game : null;
    }

    public function loadByCode(string $code): ?array
    {
        $code = self::normalizeCode($code);
        $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE code = ?');
        $stmt->execute([$code]);
        $row = $stmt->fetch();
        if (!$row) {
            return null;
        }
        $game = json_decode((string) $row['payload'], true);
        return is_array($game) ? $game : null;
    }

    public static function normalizeCode(string $code): string
    {
        $code = strtoupper(trim($code));
        // Generated codes use Crockford-ish chars (no 0/O/I/1/L). Map lookalikes.
        $code = strtr($code, ['O' => '0', 'I' => '1', 'L' => '1']);
        $code = preg_replace('/[^A-Z0-9]/', '', $code) ?? '';
        return $code;
    }

    /**
     * Load, apply due events, run $fn, save. $fn receives and returns the game
     * (or null to delete). Locked with BEGIN IMMEDIATE.
     *
     * @param callable(array):(?array) $fn
     */
    public function mutate(string $id, callable $fn): ?array
    {
        return $this->tx(function () use ($id, $fn) {
            $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');
            $stmt->execute([$id]);
            $row = $stmt->fetch();
            if (!$row) {
                throw new RuntimeException('unknown_code');
            }
            $game = json_decode((string) $row['payload'], true);
            if (!is_array($game)) {
                throw new RuntimeException('unknown_code');
            }
            $game = Engine::applyDue($game, $this->now());
            $game = $fn($game);
            if ($game === null) {
                $this->deleteGame($id);
                return null;
            }
            $this->save($game);
            return $game;
        });
    }

    public function createLobby(string $userId, string $name, ?string $avatar, array $rules = []): array
    {
        return $this->tx(function () use ($userId, $name, $avatar, $rules) {
            $now = $this->now();
            $id = Engine::generateId();
            $code = $this->uniqueCode();
            $game = Engine::newLobby($id, $code, $userId, $name, $avatar, $rules, $now);
            $this->save($game);
            $this->touchProfile($userId, $name, $avatar);
            return $game;
        });
    }

    private function uniqueCode(): string
    {
        for ($i = 0; $i < 16; $i++) {
            $code = Engine::generateCode();
            $stmt = $this->pdo->prepare('SELECT 1 FROM games WHERE code = ?');
            $stmt->execute([$code]);
            if (!$stmt->fetch()) {
                return $code;
            }
        }
        throw new RuntimeException('generic');
    }

    public function joinByCode(string $userId, string $name, ?string $avatar, string $code): array
    {
        $code = self::normalizeCode($code);
        if (strlen($code) < 4) {
            throw new RuntimeException('unknown_code');
        }
        return $this->tx(function () use ($userId, $name, $avatar, $code) {
            $stmt = $this->pdo->prepare('SELECT id, payload FROM games WHERE code = ?');
            $stmt->execute([$code]);
            $row = $stmt->fetch();
            if (!$row) {
                throw new RuntimeException('unknown_code');
            }
            $game = json_decode((string) $row['payload'], true);
            if (!is_array($game)) {
                throw new RuntimeException('unknown_code');
            }
            $game = Engine::applyDue($game, $this->now());
            if ($game['status'] === 'lobby') {
                $game = Engine::join($game, $userId, $name, $avatar, $this->now());
                $this->save($game);
            } elseif (Engine::playerIndex($game, $userId) === null) {
                throw new RuntimeException('game_started');
            } else {
                $this->save($game); // persist any due distributions
            }
            $this->touchProfile($userId, $name, $avatar);
            return $game;
        });
    }

    public function leaveLobby(string $userId, string $gameId): ?array
    {
        return $this->mutate($gameId, function (array $game) use ($userId) {
            return Engine::leaveLobby($game, $userId, $this->now());
        });
    }

    public function setRules(string $userId, string $gameId, array $rules): array
    {
        $game = $this->mutate($gameId, function (array $game) use ($userId, $rules) {
            return Engine::setLobbyRules($game, $userId, $rules);
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $game;
    }

    public function startGame(string $userId, string $gameId): array
    {
        $game = $this->mutate($gameId, function (array $game) use ($userId) {
            return Engine::start($game, $userId, $this->now());
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $game;
    }

    public function act(string $userId, string $gameId, array $action): array
    {
        $game = $this->mutate($gameId, function (array $game) use ($userId, $action) {
            return Engine::applyAction($game, $userId, $action, $this->now());
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $game;
    }

    public function setNote(string $userId, string $gameId, string $subjectId, string $text): array
    {
        $game = $this->mutate($gameId, function (array $game) use ($userId, $subjectId, $text) {
            return Engine::setNote($game, $userId, $subjectId, $text);
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $game;
    }

    public function addMessage(string $userId, string $gameId, string $toId, string $text): array
    {
        $game = $this->mutate($gameId, function (array $game) use ($userId, $toId, $text) {
            return Engine::addMessage($game, $userId, $toId, $text, $this->now());
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $game;
    }

    /**
     * Local-dev helper: set next_distribution_at to $at (or now) so applyDue
     * runs on the next mutate/present.
     */
    public function debugAdvance(string $userId, string $gameId, ?int $at = null, int $days = 1): array
    {
        if (!localDev()) {
            throw new RuntimeException('generic');
        }
        $at = $at ?? $this->now();
        $game = $this->mutate($gameId, function (array $game) use ($userId, $at, $days) {
            if (Engine::playerIndex($game, $userId) === null) {
                throw new RuntimeException('not_in_game');
            }
            if ($game['status'] !== 'running') {
                throw new RuntimeException('game_finished');
            }
            // Walk `$days` midnights into the past relative to "now" by
            // setting next_distribution_at to a due timestamp, then applyDue
            // already ran at the start of mutate — so we set it and apply again.
            $target = $at;
            $game['next_distribution_at'] = $target;
            for ($i = 0; $i < max(1, $days); $i++) {
                $game = Engine::applyDue($game, (int) $game['next_distribution_at']);
                // applyDue moves next to the following midnight; to apply more,
                // pull it back to "due" by using that new next as the time.
                if ($i < $days - 1 && $game['status'] === 'running') {
                    $game = Engine::applyDue($game, (int) $game['next_distribution_at']);
                }
            }
            return $game;
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $game;
    }

    public function present(string $userId, string $gameId): array
    {
        $game = $this->mutate($gameId, function (array $game) use ($userId) {
            if (Engine::playerIndex($game, $userId) === null) {
                throw new RuntimeException('not_in_game');
            }
            return $game;
        });
        if ($game === null) {
            throw new RuntimeException('unknown_code');
        }
        return $this->view($game, $userId);
    }

    public function view(array $game, string $userId): array
    {
        if ($game['status'] === 'lobby') {
            return Engine::lobbyView($game, $userId);
        }
        return Engine::present($game, $userId, $this->now());
    }

    public function sync(string $userId, string $gameId, int $since): array
    {
        return $this->tx(function () use ($userId, $gameId, $since) {
            $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');
            $stmt->execute([$gameId]);
            $row = $stmt->fetch();
            if (!$row) {
                throw new RuntimeException('unknown_code');
            }
            $game = json_decode((string) $row['payload'], true);
            if (!is_array($game) || Engine::playerIndex($game, $userId) === null) {
                throw new RuntimeException('not_in_game');
            }
            $before = (int) ($game['version'] ?? 0);
            $due = Engine::applyDue($game, $this->now());
            if ($due !== $game || (int) ($due['version'] ?? 0) !== $before) {
                $this->save($due);
                $game = $due;
            } else {
                $game = $due;
            }
            $version = (int) ($game['version'] ?? 0);
            $now = $this->now();
            $light = [
                'ok' => true,
                'changed' => $version !== $since,
                'version' => $version,
                'server_now' => $now,
                'status' => $game['status'],
                'next_distribution_at' => $game['next_distribution_at'] ?? null,
                'ceasefire' => Engine::ceasefireInfo($game, $now),
                'day' => (int) ($game['day'] ?? 0),
            ];
            if ($version !== $since) {
                $light['game'] = $this->view($game, $userId);
            }
            return $light;
        });
    }

    /** @return list<array> */
    public function listFor(string $userId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT g.payload FROM members m JOIN games g ON g.id = m.game_id
             WHERE m.user_id = ? ORDER BY g.updated DESC'
        );
        $stmt->execute([$userId]);
        $out = [];
        $now = $this->now();
        foreach ($stmt->fetchAll() as $row) {
            $game = json_decode((string) $row['payload'], true);
            if (!is_array($game)) {
                continue;
            }
            // Don't mutate here (listing is read-mostly); applyDue is cheap and
            // in-memory only so the menu stays accurate if a day rolled over.
            $game = Engine::applyDue($game, $now);
            $me = Engine::player($game, $userId);
            $alive = count(Engine::living($game));
            $out[] = [
                'id' => $game['id'],
                'code' => $game['code'],
                'status' => $game['status'],
                'host_id' => $game['host_id'],
                'is_host' => $game['host_id'] === $userId,
                'players' => count($game['players']),
                'alive' => $alive,
                'day' => (int) ($game['day'] ?? 0),
                'winner_id' => $game['winner_id'] ?? null,
                'draw' => !empty($game['draw']),
                'you_alive' => $me ? !empty($me['alive']) : false,
                'you_won' => ($game['winner_id'] ?? null) === $userId,
                'names' => array_map(fn ($p) => [
                    'id' => $p['id'],
                    'name' => $p['name'],
                    'color' => $p['color'] ?? null,
                    'avatar' => $p['avatar'] ?? null,
                ], $game['players']),
                'updated_at' => $game['started_at'] ?? $game['created_at'] ?? 0,
                'rules' => $game['rules'] ?? Engine::defaultRules(),
            ];
        }
        return $out;
    }

    public function ensureProfile(string $userId): array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
        $stmt->execute([$userId]);
        $row = $stmt->fetch();
        if ($row) {
            return $row;
        }
        $this->pdo->prepare(
            'INSERT INTO profiles (user_id, locale, avatar, name, updated) VALUES (?, NULL, NULL, NULL, ?)'
        )->execute([$userId, $this->now()]);
        return [
            'user_id' => $userId,
            'locale' => null,
            'avatar' => null,
            'name' => null,
            'updated' => $this->now(),
        ];
    }

    public function touchProfile(string $userId, string $name, ?string $avatar): void
    {
        $this->ensureProfile($userId);
        $this->pdo->prepare(
            'UPDATE profiles SET name = ?, avatar = COALESCE(?, avatar), updated = ? WHERE user_id = ?'
        )->execute([$name, $avatar, $this->now(), $userId]);
    }

    public function locale(string $userId): ?string
    {
        $v = $this->ensureProfile($userId)['locale'] ?? null;
        return is_string($v) && $v !== '' ? $v : null;
    }

    public function setLocale(string $userId, string $locale): string
    {
        $locale = strtolower($locale);
        if ($locale === 'zh-hans' || $locale === 'zh-cn') {
            $locale = 'zh';
        }
        if (!in_array($locale, I18n::LOCALES, true)) {
            throw new RuntimeException('generic');
        }
        $this->ensureProfile($userId);
        $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
            ->execute([$locale, $this->now(), $userId]);
        return $locale;
    }
}
