<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, HEAD, OPTIONS, POST');
header('Access-Control-Allow-Headers: *');
header('X-Robots-Tag: all');

header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

set_error_handler(function ($severity, $message, $file, $line) {
    http_response_code(500);
    echo json_encode([
        'error' => 'PHP Error',
        'severity' => $severity,
        'message' => $message,
        'file' => $file,
        'line' => $line,
    ], JSON_PRETTY_PRINT);
    exit;
});

set_exception_handler(function ($e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Uncaught Exception',
        'type' => get_class($e),
        'message' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => explode("\n", $e->getTraceAsString()),
    ], JSON_PRETTY_PRINT);
    exit;
});


require_once __DIR__ . '/folderNode.php';

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$dataRoot = __DIR__ . DIRECTORY_SEPARATOR . 'data';
$chaptersRoot = $dataRoot . DIRECTORY_SEPARATOR . 'chapters';

$allJson = loadAllJson($dataRoot);
$visited = [];
$baseUrl = getBaseUrl();

$chaptersTree = loadFolderTree($chaptersRoot);
$chapters = $chaptersTree->jsonRecursive();

usort($chapters, fn($a, $b) => ($a->number ?? 0) <=> ($b->number ?? 0));

foreach ($chapters as $chapterObj) {
    $chapter = json_decode(json_encode($chapterObj), true);
    $chapterLink = normalizeWikiPath($chapter['wikiPath'] ?? '');
    $relPath = normalizeDataRelPath($chapterLink);
    if ($relPath !== '')
        $visited[$relPath] = true;
}

$index = [];
foreach ($chapters as $chapterObj) {
    $chapter = json_decode(json_encode($chapterObj), true);
    $chapterLink = normalizeWikiPath($chapter['wikiPath'] ?? '');

    $index[] = buildChapterNode($chapter, $chapterLink, $allJson, $visited, $baseUrl);
}

echo json_encode($index, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

function loadAllJson(string $dataRoot): array
{
    $map = [];

    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dataRoot, FilesystemIterator::SKIP_DOTS)
    );

    foreach ($it as $file) {
        /** @var SplFileInfo $file */
        if (strtolower($file->getExtension()) !== 'json')
            continue;

        $path = $file->getPathname();
        $rel = str_replace('\\', '/', substr($path, strlen($dataRoot)));
        if ($rel === '')
            $rel = '/' . $file->getFilename();
        if ($rel[0] !== '/')
            $rel = '/' . $rel;

        try {
            $raw = file_get_contents($path);
            if ($raw === false)
                continue;
            $json = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
            if (!is_array($json))
                continue;
        } catch (Throwable $e) {
            continue;
        }

        $json['_relPath'] = $rel;
        $map[$rel] = $json;
    }

    return $map;
}

function buildChapterNode(array $chapter, string $chapterLink, array $allJson, array &$visited, string $baseUrl): array
{
    $name = $chapterLink !== '' ? basename($chapterLink, '.json') : ($chapter['name'] ?? 'chapter');
    $fullChapterLink = $chapterLink !== '' ? $baseUrl . $chapterLink : '';

    $node = [
        'name' => $name,
        'type' => $chapter['type'] ?? 'chapter',
        'pageType' => 'page',
        'link' => $fullChapterLink,
        'children' => [],
    ];

    $folderIncludes = extractFolderIncludes($chapter, ['subheaders']);

    $children = [];

    foreach (($chapter['subheaders'] ?? []) as $subheader) {
        if (!is_array($subheader))
            continue;

        $subNode = [
            'name' => $subheader['name'] ?? 'subheader',
            'type' => 'subheader',
            'pageType' => 'page child element',
            'link' => $fullChapterLink,
            'children' => [],
        ];

        $subIncludes = extractFolderIncludes($subheader);
        $subNode['children'] = mergeChildren(
            buildChildrenFromFolderIncludes($subIncludes, $allJson, $visited, $baseUrl)
        );

        $children[] = $subNode;
    }

    $children = mergeChildren(
        $children,
        buildChildrenFromFolderIncludes($folderIncludes, $allJson, $visited, $baseUrl)
    );

    $node['children'] = $children;

    return $node;
}

function buildChildrenFromFolderIncludes(array $folders, array $allJson, array &$visited, string $baseUrl): array
{
    $children = [];
    $rels = array_keys($allJson);
    sort($rels, SORT_NATURAL | SORT_FLAG_CASE);
    foreach ($folders as $folder) {
        $folderRel = '/' . trim(str_replace('\\', '/', $folder), '/');
        foreach ($rels as $rel) {
            if (str_starts_with($rel, $folderRel . '/')) {
                $children[] = buildDataLinkNode($rel, '', $allJson, $visited, $baseUrl);
            }
        }
    }

    return $children;
}

function buildDataLinkNode(string $relPath, string $label, array $allJson, array &$visited, string $baseUrl): array
{
    $link = $baseUrl . '/data' . $relPath;
    $json = $allJson[$relPath] ?? null;

    $name = $label;
    $type = 'linkedData';

    if (is_array($json)) {
        $type = $json['type'] ?? 'data';
        if ($name === '') {
            $name = $json['name'] ?? ($json['title'] ?? basename($relPath, '.json'));
        }
    }

    $node = [
        'name' => $name !== '' ? $name : basename($relPath, '.json'),
        'type' => $type,
        'pageType' => 'data link',
        'link' => $link,
        'children' => [],
    ];

    if (!is_array($json))
        return $node;

    if (isset($visited[$relPath]))
        return $node;

    $visited[$relPath] = true;

    $folderChildren = buildChildrenFromFolderIncludes(extractFolderIncludes($json), $allJson, $visited, $baseUrl);
    $node['children'] = mergeChildren($folderChildren);

    return $node;
}

function normalizeWikiPath(string $path): string
{
    $path = str_replace('\\', '/', $path);
    if ($path === '')
        return '';

    if (!str_starts_with($path, '/'))
        $path = '/' . $path;

    return $path;
}

function getBaseUrl(): string
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '/dataIndex.php';
    $dir = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
    return $scheme . '://' . $host . ($dir === '' ? '' : $dir);
}

function normalizeDataRelPath(string $path): string
{
    $path = trim($path);
    if ($path === '')
        return '';

    $path = str_replace('\\', '/', $path);
    if (str_starts_with($path, '/data/'))
        $path = substr($path, strlen('/data'));
    if (str_starts_with($path, 'data/'))
        $path = substr($path, strlen('data'));

    if (!str_starts_with($path, '/'))
        $path = '/' . $path;

    return $path;
}

function extractFolderIncludes(mixed $value, array $skipKeys = []): array
{
    $folders = [];

    if (is_array($value)) {
        foreach ($value as $k => $v) {
            if (in_array($k, $skipKeys, true))
                continue;
            $folders = array_merge($folders, extractFolderIncludes($v, $skipKeys));
        }
        return $folders;
    }

    if (is_string($value)) {
        return extractFolderIncludesFromString($value);
    }

    return $folders;
}

function extractFolderIncludesFromString(string $text): array
{
    $folders = [];
    $pattern = '/\[\[\[\s*([a-zA-Z0-9_.-]+)\s*\]\]\]/';

    if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $m) {
            $folders[] = $m[1];
        }
    }

    return $folders;
}

function mergeChildren(array ...$groups): array
{
    $merged = [];
    $seen = [];

    foreach ($groups as $children) {
        foreach ($children as $child) {
            if (!is_array($child))
                continue;

            $key = ($child['link'] ?? '') . '|' . ($child['name'] ?? '') . '|' . ($child['pageType'] ?? '');
            if (isset($seen[$key]))
                continue;

            $seen[$key] = true;
            $merged[] = $child;
        }
    }

    return $merged;
}
