<?php
/**
 * Shared index logic for dataIndex.php and dataBulk.php.
 * Defines functions only; produces no output.
 */

require_once __DIR__ . '/folderNode.php';

/**
 * Build the data index.
 * @return array{nodes: array, indexSha256: string, files: array<string,string>}
 *   files: "data/<folder>/<file>.json" => sha256, for every file in the index
 *   (the same set and hashes that indexSha256 is computed from), sorted by path.
 */
function buildDataIndex(): array
{
    $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);
    }

    $files = collectIndexFiles($index, $baseUrl);

    return [
        'nodes' => $index,
        'indexSha256' => indexSha256FromFiles($files),
        'files' => $files,
    ];
}

/**
 * sha256 (lowercase hex) of the exact bytes of a data file, given its path
 * relative to the web root (e.g. "/data/powers/feint.json").
 * Returns null if the file does not exist or cannot be read.
 * Results are memoised per request and keyed by path + mtime + size.
 */
function fileSha256(string $webRelPath): ?string
{
    static $cache = [];

    $webRelPath = '/' . ltrim(str_replace('\\', '/', $webRelPath), '/');
    $path = __DIR__ . $webRelPath;
    if (!is_file($path))
        return null;

    $key = $webRelPath . '|' . (int) @filemtime($path) . '|' . (int) @filesize($path);
    if (!array_key_exists($key, $cache)) {
        $hash = hash_file('sha256', $path);
        $cache[$key] = $hash === false ? null : $hash;
    }

    return $cache[$key];
}

/**
 * indexSha256 definition:
 *   Collect every node in the index (recursively) that has a non-null sha256.
 *   Take the unique data files they point to, as paths relative to the web
 *   root without a leading slash (e.g. "data/powers/feint.json").
 *   Sort them by path (byte-wise, strcmp / LC_ALL=C order) and build one line
 *   per file in sha256sum format: "<sha256 hex>  <path>\n" (two spaces).
 *   indexSha256 = lowercase hex sha256 of the concatenation of those lines.
 * Reproducible from the web/ directory with:
 *   sha256sum <those files, LC_ALL=C sorted> | sha256sum
 */
function computeIndexSha256(array $nodes, string $baseUrl): string
{
    return indexSha256FromFiles(collectIndexFiles($nodes, $baseUrl));
}

/**
 * Unique data files referenced by the index: "data/<folder>/<file>.json" => sha256,
 * sorted by path (byte-wise).
 */
function collectIndexFiles(array $nodes, string $baseUrl): array
{
    $files = [];
    collectNodeHashes($nodes, $baseUrl, $files);
    ksort($files, SORT_STRING);
    return $files;
}

/**
 * @param array<string,string> $files path => sha256, already sorted by path
 */
function indexSha256FromFiles(array $files): string
{
    $lines = '';
    foreach ($files as $path => $hash)
        $lines .= $hash . '  ' . $path . "\n";

    return hash('sha256', $lines);
}

function collectNodeHashes(array $nodes, string $baseUrl, array &$files): void
{
    $prefix = $baseUrl . '/';
    foreach ($nodes as $node) {
        if (!is_array($node))
            continue;

        $link = (string) ($node['link'] ?? '');
        if (isset($node['sha256']) && str_starts_with($link, $prefix))
            $files[substr($link, strlen($prefix))] = $node['sha256'];

        collectNodeHashes($node['children'] ?? [], $baseUrl, $files);
    }
}

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,
        'sha256' => $chapterLink !== '' ? fileSha256($chapterLink) : null,
        '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,
            'sha256' => $node['sha256'],
            '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,
        'sha256' => fileSha256('/data' . $relPath),
        '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;
}
