<?php
declare(strict_types=1);

function wikiSlugOk(string $slug): bool {
    return strlen($slug) <= 80 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) === 1;
}

/** @return list<string> */
function wikiReservedPageSlugs(): array {
    return ['nieuw', 'bewerken', 'categorie'];
}

/** @return list<string> */
function wikiReservedCategorySlugs(): array {
    return ['nieuw'];
}

function wikiSlugify(string $text): string {
    $text = mb_strtolower(trim($text), 'UTF-8');
    $text = strtr($text, [
        'à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae',
        'ç' => 'c',
        'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
        'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
        'ñ' => 'n',
        'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'ö' => 'o', 'ø' => 'o', 'œ' => 'oe',
        'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u',
        'ý' => 'y', 'ÿ' => 'y', 'ß' => 'ss',
        'ĳ' => 'ij',
    ]);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? '';
    $text = trim($text, '-');
    if (strlen($text) > 80) $text = rtrim(substr($text, 0, 80), '-');
    return $text;
}

function wikiChooseSlug(mixed $given, string $title, array $reserved): string {
    if ($given === null || $given === '') {
        $slug = wikiSlugify($title);
        if ($slug === '' || in_array($slug, $reserved, true)) {
            throw new AppException('Kies een slug: de titel levert geen bruikbare slug op.');
        }
        return $slug;
    }
    if (!is_string($given) || !wikiSlugOk($given)) {
        throw new AppException('De slug mag alleen kleine letters, cijfers en streepjes bevatten.');
    }
    if (in_array($given, $reserved, true)) throw new AppException('Die slug is gereserveerd.');
    return $given;
}

function wikiOptionalPosition(array $input): ?int {
    if (!array_key_exists('position', $input) || $input['position'] === null) return null;
    $value = $input['position'];
    if (is_string($value) && preg_match('/^[1-9][0-9]{0,4}$/', $value)) $value = (int)$value;
    if (!is_int($value) || $value < 1 || $value > 10000) {
        throw new AppException('De positie moet een geheel getal vanaf 1 zijn.');
    }
    return $value;
}

function wikiNormalizeContent(mixed $value): string {
    if (!is_string($value)) throw new AppException('De tekst moet tekst zijn.');
    $value = str_replace(["\r\n", "\r"], "\n", $value);
    if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value)) throw new AppException('De tekst bevat ongeldige tekens.');
    if (mb_strlen($value) > 100000) throw new AppException('De tekst is te lang (maximaal 100000 tekens).');
    return $value;
}

function wikiCategoryRow(string $slug): array {
    if (!wikiSlugOk($slug)) throw new AppException('Deze categorie bestaat niet.', 404);
    $row = query('SELECT * FROM wiki_categories WHERE slug=?', [$slug])->fetch();
    if (!$row) throw new AppException('Deze categorie bestaat niet.', 404);
    return $row;
}

function wikiPageRow(string $slug): array {
    if (!wikiSlugOk($slug)) throw new AppException('Deze pagina bestaat niet.', 404);
    $row = query('SELECT * FROM wiki_pages WHERE slug=?', [$slug])->fetch();
    if (!$row) throw new AppException('Deze pagina bestaat niet.', 404);
    return $row;
}

function wikiNextCategoryPosition(): int {
    return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_categories')->fetchColumn() + 1;
}

function wikiNextPagePosition(int $categoryId): int {
    return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_pages WHERE category_id=?', [$categoryId])->fetchColumn() + 1;
}

/** @return list<array{slug:string,title:string,position:int}> */
function wikiPagesInCategory(int $categoryId): array {
    $rows = query('SELECT slug, title, position FROM wiki_pages WHERE category_id=? ORDER BY position, title, slug', [$categoryId])->fetchAll();
    return array_map(fn(array $row): array => [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'position' => (int)$row['position'],
    ], $rows);
}

function wikiCategoryPayload(array $row): array {
    return [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'position' => (int)$row['position'],
        'pages' => wikiPagesInCategory((int)$row['id']),
    ];
}

function wikiHasPages(): bool {
    return (int)query('SELECT COUNT(*) FROM wiki_pages')->fetchColumn() > 0;
}

function wikiVisible(bool $admin): bool {
    return $admin || wikiHasPages();
}

function listWikiCategories(): array {
    $rows = query('SELECT * FROM wiki_categories ORDER BY position, title, slug')->fetchAll();
    return ['categories' => array_map('wikiCategoryPayload', $rows)];
}

function loadWikiCategory(string $slug): array {
    return wikiCategoryPayload(wikiCategoryRow($slug));
}

function createWikiCategory(array $input): array {
    $title = cleanText($input['title'] ?? null, 80, 'De categorietitel');
    $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedCategorySlugs());
    $position = wikiOptionalPosition($input);
    transaction(function () use ($title, $slug, $position): void {
        if (query('SELECT 1 FROM wiki_categories WHERE slug=?', [$slug])->fetchColumn()) {
            throw new AppException('Die slug is al in gebruik.', 409);
        }
        $now = time();
        query('INSERT INTO wiki_categories (slug, title, position, created, updated) VALUES (?,?,?,?,?)', [
            $slug, $title, $position ?? wikiNextCategoryPosition(), $now, $now,
        ]);
    });
    return loadWikiCategory($slug);
}

function updateWikiCategory(string $slug, array $input): array {
    foreach (['title', 'slug', 'position'] as $key) {
        if (array_key_exists($key, $input)) {
            $present = true;
            break;
        }
    }
    if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
    $stored = $slug;
    transaction(function () use ($slug, $input, &$stored): void {
        $row = wikiCategoryRow($slug);
        $title = array_key_exists('title', $input) ? cleanText($input['title'], 80, 'De categorietitel') : $row['title'];
        $newSlug = array_key_exists('slug', $input)
            ? wikiChooseSlug($input['slug'], $title, wikiReservedCategorySlugs())
            : $row['slug'];
        $position = array_key_exists('position', $input) ? wikiOptionalPosition($input) : (int)$row['position'];
        if ($position === null) $position = (int)$row['position'];
        $clash = query('SELECT 1 FROM wiki_categories WHERE slug=? AND id<>?', [$newSlug, $row['id']])->fetchColumn();
        if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
        query('UPDATE wiki_categories SET slug=?, title=?, position=?, updated=? WHERE id=?', [
            $newSlug, $title, $position, time(), $row['id'],
        ]);
        $stored = $newSlug;
    });
    return loadWikiCategory($stored);
}

function deleteWikiCategory(string $slug): string {
    transaction(function () use ($slug): void {
        $row = wikiCategoryRow($slug);
        $count = (int)query('SELECT COUNT(*) FROM wiki_pages WHERE category_id=?', [$row['id']])->fetchColumn();
        if ($count > 0) throw new AppException('Deze categorie heeft nog pagina\'s. Verplaats of verwijder die eerst.', 409);
        query('DELETE FROM wiki_categories WHERE id=?', [$row['id']]);
    });
    return $slug;
}

function wikiPageSummary(array $row): array {
    return [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'position' => (int)$row['position'],
        'updated' => (int)$row['updated'],
        'category' => ['slug' => $row['category_slug'], 'title' => $row['category_title']],
    ];
}

function listWikiPages(?string $categorySlug, ?string $query): array {
    if ($categorySlug !== null && $categorySlug !== '') {
        if (!wikiSlugOk($categorySlug)) throw new AppException('De categorie moet een slug zijn.');
        $category = wikiCategoryRow($categorySlug);
        $rows = query(
            'SELECT p.*, c.slug AS category_slug, c.title AS category_title
             FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
             WHERE p.category_id=? ORDER BY p.position, p.title, p.slug',
            [$category['id']]
        )->fetchAll();
    } else {
        $rows = query(
            'SELECT p.*, c.slug AS category_slug, c.title AS category_title
             FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
             ORDER BY c.position, p.position, p.title, p.slug'
        )->fetchAll();
    }
    $needle = $query === null ? '' : trim($query);
    if ($needle !== '') {
        if (mb_strlen($needle) > 200) throw new AppException('De zoekterm is te lang (maximaal 200 tekens).');
        $folded = mb_strtolower($needle, 'UTF-8');
        $rows = array_values(array_filter($rows, function (array $row) use ($folded): bool {
            return str_contains(mb_strtolower($row['title'], 'UTF-8'), $folded)
                || str_contains(mb_strtolower($row['content'], 'UTF-8'), $folded);
        }));
    }
    return array_map('wikiPageSummary', $rows);
}

/**
 * @return list<array{anchor:string,title:?string,blocks:list<array{inlines:list<array<string,mixed>>}>}>
 */
function parseWikiChapters(string $content): array {
    $content = str_replace(["\r\n", "\r"], "\n", $content);
    $lines = $content === '' ? [] : explode("\n", $content);
    $sections = [];
    $title = null;
    $buffer = [];
    $open = false;
    foreach ($lines as $line) {
        if (preg_match('/^##[ \t]*$/u', $line)) throw new AppException('Een hoofdstuk heeft een titel nodig.');
        if (preg_match('/^##[ \t]+(.*)$/u', $line, $match)) {
            $heading = trim($match[1]);
            if ($heading === '') throw new AppException('Een hoofdstuk heeft een titel nodig.');
            if (mb_strlen($heading) > 200) throw new AppException('Een hoofdstuktitel is te lang (maximaal 200 tekens).');
            if ($open || trim(implode("\n", $buffer)) !== '') {
                $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
            }
            $buffer = [];
            $open = true;
            $title = $heading;
            continue;
        }
        $buffer[] = $line;
    }
    if ($open || trim(implode("\n", $buffer)) !== '') {
        $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
    }
    return wikiAssignAnchors($sections);
}

/** @param list<array{title:?string,body:string}> $sections */
function wikiAssignAnchors(array $sections): array {
    $used = [];
    $chapters = [];
    foreach ($sections as $section) {
        if ($section['title'] === null) {
            $base = 'inleiding';
        } else {
            $base = wikiSlugify($section['title']);
            if ($base === '') $base = 'hoofdstuk';
        }
        $anchor = $base;
        $n = 2;
        while (isset($used[$anchor])) {
            $anchor = $base.'-'.$n;
            $n++;
        }
        $used[$anchor] = true;
        $chapters[] = [
            'anchor' => $anchor,
            'title' => $section['title'],
            'blocks' => wikiParagraphs($section['body']),
        ];
    }
    return $chapters;
}

/**
 * Blokken binnen een hoofdstuk. Een lege regel scheidt alinea's. Een gewone
 * regeleinde wordt een spatie, twee spaties of een backslash aan het regeleinde
 * een zichtbare breuk. Lijsten, citaten, nadruk, code en externe links komen
 * hierbij; ##-hoofdstukken zijn dan al apart gezet.
 *
 * @return list<array<string,mixed>>
 */
function wikiParagraphs(string $body): array {
    $body = str_replace(["\r\n", "\r"], "\n", $body);
    $lines = $body === '' ? [] : explode("\n", $body);
    return wikiParseBlockLines($lines, 0, count($lines), 0)['blocks'];
}

/** @return array{blocks:list<array<string,mixed>>,next:int} */
function wikiParseBlockLines(array $lines, int $i, int $n, int $depth): array {
    if ($depth > 30) {
        $text = trim(implode(' ', array_map(fn(string $line): string => trim($line), $lines)));
        $inlines = $text === '' ? [] : wikiParseInlines($text);
        return ['blocks' => $inlines ? [['type' => 'paragraph', 'inlines' => $inlines]] : [], 'next' => $n];
    }
    $blocks = [];
    while ($i < $n) {
        if (trim($lines[$i]) === '') { $i++; continue; }
        $list = wikiMatchList($lines[$i]);
        if ($list) {
            $parsed = wikiParseList($lines, $i, $n, $list['indent'], $list['ordered'], $depth);
            if ($parsed['block']) $blocks[] = $parsed['block'];
            $i = $parsed['next'];
            continue;
        }
        if (wikiIsQuoteLine($lines[$i])) {
            $parsed = wikiParseQuote($lines, $i, $n, $depth);
            if ($parsed['block']) $blocks[] = $parsed['block'];
            $i = $parsed['next'];
            continue;
        }
        $parsed = wikiParseParagraph($lines, $i, $n);
        if ($parsed['block']) $blocks[] = $parsed['block'];
        $i = $parsed['next'];
    }
    return ['blocks' => $blocks, 'next' => $i];
}

function wikiIsQuoteLine(string $line): bool {
    return preg_match('/^[ \t]*>/u', $line) === 1;
}

/** @return array{block:?array<string,mixed>,next:int} */
function wikiParseQuote(array $lines, int $i, int $n, int $depth): array {
    $collected = [];
    while ($i < $n && preg_match('/^[ \t]*> ?(.*)$/u', $lines[$i], $match)) {
        $collected[] = $match[1];
        $i++;
    }
    $inner = wikiParseBlockLines($collected, 0, count($collected), $depth + 1)['blocks'];
    return ['block' => $inner ? ['type' => 'quote', 'blocks' => $inner] : null, 'next' => $i];
}

/** @return ?array{indent:int,ordered:bool,number:?int,text:string} */
function wikiMatchList(string $line): ?array {
    if (preg_match('/^([ \t]*)([-*]|\d{1,9}\.)([ \t]+)(.*)$/u', $line, $match) !== 1) return null;
    $marker = $match[2];
    $ordered = str_ends_with($marker, '.');
    return [
        'indent' => wikiIndentColumns($match[1]),
        'ordered' => $ordered,
        'number' => $ordered ? (int)$marker : null,
        'text' => $match[4],
    ];
}

function wikiIndentColumns(string $whitespace): int {
    $columns = 0;
    $length = strlen($whitespace);
    for ($i = 0; $i < $length; $i++) $columns += $whitespace[$i] === "\t" ? 4 : 1;
    return $columns;
}

function wikiLeadingColumns(string $line): int {
    if (preg_match('/^[ \t]*/', $line, $match) !== 1) return 0;
    return wikiIndentColumns($match[0]);
}

/** @return array{block:?array<string,mixed>,next:int} */
function wikiParseList(array $lines, int $i, int $n, int $base, bool $ordered, int $depth): array {
    $items = [];
    $start = null;
    while ($i < $n) {
        while ($i < $n && trim($lines[$i]) === '') {
            $k = $i + 1;
            while ($k < $n && trim($lines[$k]) === '') $k++;
            $sibling = $k < $n ? wikiMatchList($lines[$k]) : null;
            if ($sibling && $sibling['indent'] === $base && $sibling['ordered'] === $ordered) {
                $i = $k;
                break;
            }
            break 2;
        }
        if ($i >= $n) break;
        $item = wikiMatchList($lines[$i]);
        if (!$item || $item['indent'] !== $base || $item['ordered'] !== $ordered) break;
        if ($start === null) $start = $item['number'];
        $i++;
        $body = [$item['text']];
        while ($i < $n) {
            if (trim($lines[$i]) === '') {
                $k = $i + 1;
                while ($k < $n && trim($lines[$k]) === '') $k++;
                if ($k >= $n) { $i = $n; break; }
                $next = wikiMatchList($lines[$k]);
                if ($next && $next['indent'] === $base && $next['ordered'] === $ordered) {
                    $i = $k;
                    break;
                }
                if ($next && $next['indent'] <= $base) break;
                if (wikiLeadingColumns($lines[$k]) <= $base) break;
                $body[] = '';
                $i++;
                continue;
            }
            $next = wikiMatchList($lines[$i]);
            if ($next && $next['indent'] <= $base) break;
            if (wikiLeadingColumns($lines[$i]) <= $base) break;
            $body[] = $lines[$i];
            $i++;
        }
        $items[] = ['blocks' => wikiParseBlockLines($body, 0, count($body), $depth + 1)['blocks']];
    }
    if (!$items) return ['block' => null, 'next' => $i];
    $block = ['type' => 'list', 'ordered' => $ordered, 'items' => $items];
    if ($ordered && $start !== null && $start !== 1) $block['start'] = $start;
    return ['block' => $block, 'next' => $i];
}

/** @return array{block:?array<string,mixed>,next:int} */
function wikiParseParagraph(array $lines, int $i, int $n): array {
    $chunks = [];
    while ($i < $n) {
        $line = $lines[$i];
        if (trim($line) === '' || wikiMatchList($line) || wikiIsQuoteLine($line)) break;
        $chunks[] = $line;
        $i++;
    }
    $inlines = wikiJoinParagraph($chunks);
    return ['block' => $inlines ? ['type' => 'paragraph', 'inlines' => $inlines] : null, 'next' => $i];
}

/** @return list<array<string,mixed>> */
function wikiJoinParagraph(array $rawLines): array {
    $segments = [];
    foreach ($rawLines as $line) {
        if (trim($line) === '') continue;
        [$text, $hard] = wikiSplitHard($line);
        if ($text === '' && !$hard) continue;
        $segments[] = ['text' => $text, 'hard' => $hard];
    }
    if (!$segments) return [];
    $joined = '';
    foreach ($segments as $index => $segment) {
        if ($index > 0) $joined .= $segments[$index - 1]['hard'] ? "\n" : ' ';
        $joined .= $segment['text'];
    }
    return wikiParseInlines($joined);
}

/** @return array{0:string,1:bool} */
function wikiSplitHard(string $line): array {
    if (preg_match('/^(.*?)([ \t]{2,})$/u', $line, $match) === 1 && trim($match[1]) !== '') {
        return [trim($match[1]), true];
    }
    $trimmed = rtrim($line, " \t");
    if ($trimmed !== '' && str_ends_with($trimmed, '\\') && wikiEndsWithOddBackslash($trimmed)) {
        return [trim(substr($trimmed, 0, -1)), true];
    }
    return [trim($line), false];
}

function wikiEndsWithOddBackslash(string $line): bool {
    $count = 0;
    for ($i = strlen($line) - 1; $i >= 0 && $line[$i] === '\\'; $i--) $count++;
    return $count % 2 === 1;
}

/** @return list<array<string,mixed>> */
function wikiParseInlines(string $text): array {
    if ($text === '') return [];
    $scanned = wikiScanInlines($text, 0, strlen($text), false);
    return wikiMatchEmphasis($scanned['tokens']);
}

/**
 * @return array{tokens:list<array<string,mixed>>,next:int,stopped:bool}
 */
function wikiScanInlines(string $text, int $i, int $end, bool $inLabel): array {
    $tokens = [];
    $buffer = '';
    $flush = function () use (&$tokens, &$buffer): void {
        if ($buffer !== '') {
            $tokens[] = ['kind' => 'text', 'text' => $buffer];
            $buffer = '';
        }
    };
    while ($i < $end) {
        if ($inLabel && $text[$i] === ']') {
            $flush();
            return ['tokens' => $tokens, 'next' => $i, 'stopped' => true];
        }
        if ($text[$i] === "\n") {
            $flush();
            $tokens[] = ['kind' => 'break'];
            $i++;
            continue;
        }
        if ($text[$i] === '\\' && $i + 1 < $end) {
            $next = wikiCharAt($text, $i + 1, $end);
            if (wikiEscapable($next)) {
                $buffer .= $next;
                $i += 1 + strlen($next);
                continue;
            }
        }
        if ($text[$i] === '`') {
            $code = wikiTryCode($text, $i, $end);
            if ($code) {
                $flush();
                $tokens[] = $code['token'];
                $i = $code['next'];
                continue;
            }
        }
        if ($text[$i] === '[' && $i + 1 < $end && $text[$i + 1] === '[') {
            $link = wikiTryWikiLink($text, $i, $end);
            if ($link) {
                $flush();
                $tokens[] = ['kind' => 'wiki', 'link' => $link['link']];
                $i = $link['next'];
                continue;
            }
        }
        if (!$inLabel && $text[$i] === '[') {
            $link = wikiTryExternalLink($text, $i, $end);
            if ($link) {
                $flush();
                $tokens[] = $link['token'];
                $i = $link['next'];
                continue;
            }
        }
        if ($text[$i] === '*' || $text[$i] === '_') {
            $marker = $text[$i];
            $run = 0;
            while ($i + $run < $end && $text[$i + $run] === $marker) $run++;
            $before = wikiCharClass(wikiPrevChar($text, $i));
            $after = wikiCharClass(wikiCharAt($text, $i + $run, $end));
            $flush();
            $tokens[] = [
                'kind' => 'delim',
                'marker' => $marker,
                'len' => $run,
                'canOpen' => wikiCanOpen($before, $after, $marker),
                'canClose' => wikiCanClose($before, $after, $marker),
            ];
            $i += $run;
            continue;
        }
        $char = wikiCharAt($text, $i, $end);
        if ($char === '') { $i++; continue; }
        $buffer .= $char;
        $i += strlen($char);
    }
    $flush();
    return ['tokens' => $tokens, 'next' => $i, 'stopped' => false];
}

function wikiEscapable(string $char): bool {
    return $char !== '' && str_contains('\\`*_{}[]()#+-.!|>', $char);
}

function wikiCharAt(string $text, int $byte, int $end): string {
    if ($byte < 0 || $byte >= $end) return '';
    $slice = substr($text, $byte, min(4, $end - $byte));
    if (preg_match('/\A./us', $slice, $match) === 1) return $match[0];
    return $text[$byte];
}

function wikiPrevChar(string $text, int $byte): string {
    if ($byte <= 0) return '';
    $start = max(0, $byte - 4);
    $slice = substr($text, $start, $byte - $start);
    if (preg_match('/.\z/us', $slice, $match) === 1) return $match[0];
    return $text[$byte - 1];
}

function wikiCharClass(string $char): string {
    if ($char === '') return 'edge';
    if (preg_match('/\A\s\z/u', $char) === 1) return 'space';
    if (preg_match('/\A[\p{L}\p{N}]\z/u', $char) === 1) return 'word';
    return 'punct';
}

function wikiLeftFlanking(string $before, string $after): bool {
    if ($after === 'space' || $after === 'edge') return false;
    if ($after === 'punct' && $before !== 'space' && $before !== 'edge' && $before !== 'punct') return false;
    return true;
}

function wikiRightFlanking(string $before, string $after): bool {
    if ($before === 'space' || $before === 'edge') return false;
    if ($before === 'punct' && $after !== 'space' && $after !== 'edge' && $after !== 'punct') return false;
    return true;
}

function wikiCanOpen(string $before, string $after, string $marker): bool {
    if (!wikiLeftFlanking($before, $after)) return false;
    if ($marker === '_' && wikiRightFlanking($before, $after) && $before !== 'punct') return false;
    return true;
}

function wikiCanClose(string $before, string $after, string $marker): bool {
    if (!wikiRightFlanking($before, $after)) return false;
    if ($marker === '_' && wikiLeftFlanking($before, $after) && $after !== 'punct') return false;
    return true;
}

/** @return ?array{token:array<string,mixed>,next:int} */
function wikiTryCode(string $text, int $i, int $end): ?array {
    if ($text[$i] !== '`') return null;
    $run = 0;
    while ($i + $run < $end && $text[$i + $run] === '`') $run++;
    $j = $i + $run;
    while ($j < $end) {
        if ($text[$j] !== '`') { $j++; continue; }
        $close = 0;
        while ($j + $close < $end && $text[$j + $close] === '`') $close++;
        if ($close === $run) {
            $content = substr($text, $i + $run, $j - ($i + $run));
            $content = str_replace("\n", ' ', $content);
            if (strlen($content) >= 2 && $content[0] === ' ' && str_ends_with($content, ' ') && trim($content) !== '') {
                $content = substr($content, 1, -1);
            }
            return ['token' => ['kind' => 'code', 'text' => $content], 'next' => $j + $run];
        }
        $j += $close;
    }
    return null;
}

/** @return ?array{link:array<string,mixed>,next:int} */
function wikiTryWikiLink(string $text, int $i, int $end): ?array {
    if ($i + 3 >= $end || $text[$i] !== '[' || $text[$i + 1] !== '[') return null;
    if (preg_match('/\A\[\[([^\[\]\n]+)\]\]/u', substr($text, $i, $end - $i), $match) !== 1) return null;
    return ['link' => wikiRawLink($match[1]), 'next' => $i + strlen($match[0])];
}

/** @return ?array{token:array<string,mixed>,next:int} */
function wikiTryExternalLink(string $text, int $i, int $end): ?array {
    if ($text[$i] !== '[') return null;
    $label = wikiScanInlines($text, $i + 1, $end, true);
    if (!$label['stopped']) return null;
    $j = $label['next'];
    if ($j + 1 >= $end || $text[$j + 1] !== '(') return null;
    $urlStart = $j + 2;
    if ($urlStart >= $end) return null;
    $url = '';
    $next = $urlStart;
    if ($text[$urlStart] === '<') {
        $close = strpos($text, '>', $urlStart + 1);
        if ($close === false || $close >= $end || $close + 1 >= $end || $text[$close + 1] !== ')') return null;
        $url = substr($text, $urlStart + 1, $close - $urlStart - 1);
        $next = $close + 2;
    } else {
        $depth = 0;
        $k = $urlStart;
        while ($k < $end) {
            $char = wikiCharAt($text, $k, $end);
            if ($char === '\\' && $k + strlen($char) < $end) {
                $escaped = wikiCharAt($text, $k + 1, $end);
                if (wikiEscapable($escaped)) {
                    $url .= $escaped;
                    $k += 1 + strlen($escaped);
                    continue;
                }
            }
            if ($char === '(') { $depth++; $url .= '('; $k++; continue; }
            if ($char === ')') {
                if ($depth === 0) break;
                $depth--;
                $url .= ')';
                $k++;
                continue;
            }
            if (wikiCharClass($char) === 'space') return null;
            $url .= $char;
            $k += strlen($char);
        }
        if ($k >= $end || $text[$k] !== ')') return null;
        $next = $k + 1;
    }
    $safe = wikiSafeUrl($url);
    if ($safe === null) return null;
    $children = $label['tokens'];
    if (!$children) $children = [['kind' => 'text', 'text' => $safe]];
    return ['token' => ['kind' => 'url', 'href' => $safe, 'children' => $children], 'next' => $next];
}

function wikiSafeUrl(string $url): ?string {
    $url = trim($url);
    if ($url === '' || strlen($url) > 2000) return null;
    if (preg_match('/[\x00-\x20\x7F<>"\'\\\\]/', $url) === 1) return null;
    if (preg_match('#\Ahttps?://[^\s/]+#i', $url) === 1) return $url;
    if (preg_match('#\Amailto:[^@\s]+@[^@\s]+#i', $url) === 1) return $url;
    return null;
}

/** @param list<array<string,mixed>> $tokens */
function wikiMatchEmphasis(array $tokens): array {
    $budget = count($tokens) + 1;
    foreach ($tokens as $token) {
        if (($token['kind'] ?? '') === 'delim') $budget += (int)($token['len'] ?? 0);
    }
    $guard = 0;
    while ($guard++ < $budget) {
        $found = wikiFirstEmphasisMatch($tokens);
        if ($found === null) break;
        [$open, $close, $use] = $found;
        $inner = array_slice($tokens, $open + 1, $close - $open - 1);
        $tokens[$open]['len'] -= $use;
        $tokens[$close]['len'] -= $use;
        $node = ['kind' => $use === 2 ? 'strong' : 'em', 'children' => $inner];
        $replacement = [];
        if ($tokens[$open]['len'] > 0) $replacement[] = $tokens[$open];
        $replacement[] = $node;
        if ($tokens[$close]['len'] > 0) $replacement[] = $tokens[$close];
        array_splice($tokens, $open, $close - $open + 1, $replacement);
    }
    return wikiTokensToInlines($tokens);
}

/** @param list<array<string,mixed>> $tokens
 *  @return ?array{0:int,1:int,2:int}
 */
function wikiFirstEmphasisMatch(array $tokens): ?array {
    $count = count($tokens);
    for ($close = 0; $close < $count; $close++) {
        $closer = $tokens[$close];
        if (($closer['kind'] ?? '') !== 'delim' || empty($closer['canClose']) || (int)$closer['len'] < 1) continue;
        for ($open = $close - 1; $open >= 0; $open--) {
            $opener = $tokens[$open];
            if (($opener['kind'] ?? '') !== 'delim' || empty($opener['canOpen']) || (int)$opener['len'] < 1) continue;
            if ($opener['marker'] !== $closer['marker']) continue;
            if (!wikiDelimLengthsOk((int)$opener['len'], (int)$closer['len'])) continue;
            $use = ((int)$opener['len'] >= 2 && (int)$closer['len'] >= 2) ? 2 : 1;
            return [$open, $close, $use];
        }
    }
    return null;
}

function wikiDelimLengthsOk(int $opener, int $closer): bool {
    if ($opener < 1 || $closer < 1) return false;
    if (($opener % 3 === 0 || $closer % 3 === 0) && (($opener + $closer) % 3 !== 0)) return false;
    return true;
}

/** @param list<array<string,mixed>> $tokens
 *  @return list<array<string,mixed>>
 */
function wikiTokensToInlines(array $tokens): array {
    $inlines = [];
    $buffer = '';
    $flush = function () use (&$inlines, &$buffer): void {
        if ($buffer !== '') {
            $inlines[] = ['type' => 'text', 'text' => $buffer];
            $buffer = '';
        }
    };
    foreach ($tokens as $token) {
        $kind = $token['kind'] ?? '';
        if ($kind === 'text') { $buffer .= $token['text']; continue; }
        if ($kind === 'delim') {
            $length = (int)($token['len'] ?? 0);
            if ($length > 0) $buffer .= str_repeat((string)$token['marker'], $length);
            continue;
        }
        $flush();
        if ($kind === 'break') { $inlines[] = ['type' => 'break']; continue; }
        if ($kind === 'code') { $inlines[] = ['type' => 'code', 'text' => (string)($token['text'] ?? '')]; continue; }
        if ($kind === 'wiki') { $inlines[] = $token['link']; continue; }
        if ($kind === 'url') {
            $children = wikiMatchEmphasis($token['children'] ?? []);
            if (!$children) $children = [['type' => 'text', 'text' => (string)$token['href']]];
            $inlines[] = ['type' => 'url', 'href' => (string)$token['href'], 'inlines' => $children];
            continue;
        }
        if ($kind === 'strong' || $kind === 'em') {
            $inlines[] = ['type' => $kind, 'inlines' => wikiTokensToInlines($token['children'] ?? [])];
        }
    }
    $flush();
    return $inlines;
}

/** @return array<string,mixed> */
function wikiRawLink(string $inner): array {
    $label = null;
    $target = $inner;
    $bar = strpos($inner, '|');
    if ($bar !== false) {
        $target = substr($inner, 0, $bar);
        $label = trim(substr($inner, $bar + 1));
        if ($label === '') $label = null;
    }
    $target = trim($target);
    $page = null;
    $anchor = null;
    if (str_starts_with($target, '#')) {
        $anchor = substr($target, 1);
    } elseif (str_contains($target, '#')) {
        [$page, $anchor] = explode('#', $target, 2);
        if ($page === '') $page = null;
    } else {
        $page = $target;
    }
    $pageOk = $page === null || wikiSlugOk($page);
    $anchorOk = $anchor === null || ($anchor !== '' && wikiSlugOk($anchor));
    $valid = $pageOk && $anchorOk && ($page !== null || ($anchor !== null && $anchor !== ''));
    return [
        'type' => 'link',
        'page' => $page,
        'anchor' => $anchor === '' ? null : $anchor,
        'label' => $label,
        'raw' => trim($inner),
        'valid' => $valid,
    ];
}

/** @return array<string,array{title:string,anchors:array<string,string>,chapters:list<array<string,mixed>>}> */
function wikiCatalog(): array {
    $rows = query('SELECT slug, title, content FROM wiki_pages')->fetchAll();
    $catalog = [];
    foreach ($rows as $row) {
        $chapters = parseWikiChapters($row['content']);
        $anchors = [];
        foreach ($chapters as $chapter) $anchors[$chapter['anchor']] = $chapter['title'] ?? 'Inleiding';
        $catalog[$row['slug']] = [
            'title' => $row['title'],
            'anchors' => $anchors,
            'chapters' => $chapters,
        ];
    }
    return $catalog;
}

/** @param array<string,mixed> $link */
function wikiResolveLink(array $link, string $pageSlug, array $catalog): array {
    $targetPage = $link['page'] ?? $pageSlug;
    $anchor = $link['anchor'];
    $known = ($link['valid'] && is_string($targetPage) && isset($catalog[$targetPage])) ? $catalog[$targetPage] : null;
    $broken = $known === null;
    $chapterTitle = null;
    if (!$broken && $anchor !== null) {
        if (!isset($known['anchors'][$anchor])) $broken = true;
        else $chapterTitle = $known['anchors'][$anchor];
    }
    $text = $link['label'];
    if ($text === null || $text === '') {
        if ($broken) $text = $link['raw'];
        elseif ($anchor !== null) $text = $chapterTitle ?? $anchor;
        else $text = $known['title'];
    }
    return [
        'type' => 'link',
        'page' => $broken ? null : $targetPage,
        'anchor' => $broken ? null : $anchor,
        'text' => $text,
        'broken' => $broken,
    ];
}

/** @param list<array<string,mixed>> $chapters */
function wikiResolveChapters(array $chapters, string $pageSlug, array $catalog): array {
    $resolved = [];
    foreach ($chapters as $chapter) {
        $resolved[] = [
            'anchor' => $chapter['anchor'],
            'title' => $chapter['title'],
            'blocks' => wikiResolveBlocks($chapter['blocks'], $pageSlug, $catalog),
        ];
    }
    return $resolved;
}

/** @param list<array<string,mixed>> $blocks
 *  @return list<array<string,mixed>>
 */
function wikiResolveBlocks(array $blocks, string $pageSlug, array $catalog): array {
    $resolved = [];
    foreach ($blocks as $block) {
        $type = $block['type'] ?? 'paragraph';
        if ($type === 'list') {
            $items = [];
            foreach ($block['items'] ?? [] as $item) {
                $items[] = ['blocks' => wikiResolveBlocks($item['blocks'] ?? [], $pageSlug, $catalog)];
            }
            $copy = ['type' => 'list', 'ordered' => (bool)($block['ordered'] ?? false), 'items' => $items];
            if (isset($block['start'])) $copy['start'] = (int)$block['start'];
            $resolved[] = $copy;
            continue;
        }
        if ($type === 'quote') {
            $inner = wikiResolveBlocks($block['blocks'] ?? [], $pageSlug, $catalog);
            if ($inner) $resolved[] = ['type' => 'quote', 'blocks' => $inner];
            continue;
        }
        $inlines = wikiResolveInlines($block['inlines'] ?? [], $pageSlug, $catalog, false);
        if ($inlines) $resolved[] = ['type' => 'paragraph', 'inlines' => $inlines];
    }
    return $resolved;
}

/** @param list<array<string,mixed>> $inlines
 *  @return list<array<string,mixed>>
 */
function wikiResolveInlines(array $inlines, string $pageSlug, array $catalog, bool $insideUrl): array {
    $resolved = [];
    foreach ($inlines as $inline) {
        $type = $inline['type'] ?? '';
        if ($type === 'text') {
            if (($inline['text'] ?? '') !== '') $resolved[] = ['type' => 'text', 'text' => $inline['text']];
            continue;
        }
        if ($type === 'break') { $resolved[] = ['type' => 'break']; continue; }
        if ($type === 'code') { $resolved[] = ['type' => 'code', 'text' => (string)($inline['text'] ?? '')]; continue; }
        if ($type === 'link') {
            $link = wikiResolveLink($inline, $pageSlug, $catalog);
            if ($insideUrl) {
                if ($link['text'] !== '') $resolved[] = ['type' => 'text', 'text' => $link['text']];
                continue;
            }
            $resolved[] = $link;
            continue;
        }
        if ($type === 'strong' || $type === 'em') {
            $resolved[] = [
                'type' => $type,
                'inlines' => wikiResolveInlines($inline['inlines'] ?? [], $pageSlug, $catalog, $insideUrl),
            ];
            continue;
        }
        if ($type === 'url') {
            $href = wikiSafeUrl((string)($inline['href'] ?? ''));
            if ($href === null) {
                foreach (wikiResolveInlines($inline['inlines'] ?? [], $pageSlug, $catalog, true) as $child) $resolved[] = $child;
                continue;
            }
            $children = wikiResolveInlines($inline['inlines'] ?? [], $pageSlug, $catalog, true);
            if (!$children) $children = [['type' => 'text', 'text' => $href]];
            $resolved[] = ['type' => 'url', 'href' => $href, 'inlines' => $children];
        }
    }
    return $resolved;
}

function loadWikiPage(string $slug): array {
    $page = wikiPageRow($slug);
    $category = query('SELECT slug, title FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
    if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
    $catalog = wikiCatalog();
    $chapters = wikiResolveChapters($catalog[$page['slug']]['chapters'], $page['slug'], $catalog);
    return [
        'slug' => $page['slug'],
        'title' => $page['title'],
        'position' => (int)$page['position'],
        'category' => ['slug' => $category['slug'], 'title' => $category['title']],
        'content' => $page['content'],
        'created' => (int)$page['created'],
        'updated' => (int)$page['updated'],
        'chapters' => $chapters,
    ];
}

function createWikiPage(array $input): array {
    $title = cleanText($input['title'] ?? null, 200, 'De paginatitel');
    if (!is_string($input['category'] ?? null) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
    $content = wikiNormalizeContent($input['content'] ?? '');
    parseWikiChapters($content);
    $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedPageSlugs());
    $position = wikiOptionalPosition($input);
    transaction(function () use ($title, $input, $content, $slug, $position): void {
        $category = wikiCategoryRow($input['category']);
        if (query('SELECT 1 FROM wiki_pages WHERE slug=?', [$slug])->fetchColumn()) {
            throw new AppException('Die slug is al in gebruik.', 409);
        }
        $now = time();
        query('INSERT INTO wiki_pages (category_id, slug, title, content, position, created, updated) VALUES (?,?,?,?,?,?,?)', [
            $category['id'], $slug, $title, $content, $position ?? wikiNextPagePosition((int)$category['id']), $now, $now,
        ]);
    });
    return loadWikiPage($slug);
}

function updateWikiPage(string $slug, array $input): array {
    foreach (['title', 'slug', 'position', 'content', 'category'] as $key) {
        if (array_key_exists($key, $input)) {
            $present = true;
            break;
        }
    }
    if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
    $stored = $slug;
    transaction(function () use ($slug, $input, &$stored): void {
        $page = wikiPageRow($slug);
        $title = array_key_exists('title', $input) ? cleanText($input['title'], 200, 'De paginatitel') : $page['title'];
        $newSlug = array_key_exists('slug', $input)
            ? wikiChooseSlug($input['slug'], $title, wikiReservedPageSlugs())
            : $page['slug'];
        $content = array_key_exists('content', $input) ? wikiNormalizeContent($input['content']) : $page['content'];
        parseWikiChapters($content);
        if (array_key_exists('category', $input)) {
            if (!is_string($input['category']) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
            $category = wikiCategoryRow($input['category']);
        } else {
            $category = query('SELECT * FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
            if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
        }
        $moved = (int)$category['id'] !== (int)$page['category_id'];
        if (array_key_exists('position', $input)) $position = wikiOptionalPosition($input);
        else $position = $moved ? null : (int)$page['position'];
        if ($position === null) $position = wikiNextPagePosition((int)$category['id']);
        $clash = query('SELECT 1 FROM wiki_pages WHERE slug=? AND id<>?', [$newSlug, $page['id']])->fetchColumn();
        if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
        query('UPDATE wiki_pages SET category_id=?, slug=?, title=?, content=?, position=?, updated=? WHERE id=?', [
            $category['id'], $newSlug, $title, $content, $position, time(), $page['id'],
        ]);
        $stored = $newSlug;
    });
    return loadWikiPage($stored);
}

function deleteWikiPage(string $slug): string {
    transaction(function () use ($slug): void {
        $page = wikiPageRow($slug);
        query('DELETE FROM wiki_pages WHERE id=?', [$page['id']]);
    });
    return $slug;
}
