<?php

final class FolderNode
{
    public string $name;
    public string $path;

    /** @var array<string, FolderNode> keyed by folder name */
    public array $children = [];

    /** @var array<string, mixed> keyed by filename */
    public array $jsonFiles = [];

    public function __construct(string $name, string $path)
    {
        $this->name = $name;
        $this->path = $path;
    }

    /**
     * Return parsed JSON objects in THIS folder only (non-recursive),
     * as a plain numerically-indexed array.
     */
    public function jsonNonRecursive(): array
    {
        return array_values($this->jsonFiles);
    }

    /**
     * Return parsed JSON objects in THIS folder and all subfolders (recursive).
     */
    public function jsonRecursive(): array
    {
        $all = array_values($this->jsonFiles);
        foreach ($this->children as $child) {
            $all = array_merge($all, $child->jsonRecursive());
        }
        return $all;
    }

    /**
     * Find a folder anywhere in the tree by name (first match depth-first).
     */
    public function findFolder(string $name): ?FolderNode
    {
        if ($this->name === $name)
            return $this;

        foreach ($this->children as $child) {
            $found = $child->findFolder($name);
            if ($found)
                return $found;
        }
        return null;
    }
}

/**
 * Build a FolderNode tree from a root directory.
 */
function loadFolderTree(string $rootPath): FolderNode
{
    $rootPath = rtrim($rootPath, DIRECTORY_SEPARATOR);
    if (!is_dir($rootPath)) {
        throw new InvalidArgumentException("Not a directory: {$rootPath}");
    }

    $name = basename($rootPath);
    $node = new FolderNode($name, $rootPath);

    $it = new DirectoryIterator($rootPath);
    foreach ($it as $entry) {
        if ($entry->isDot())
            continue;

        $fullPath = $entry->getPathname();

        if ($entry->isDir()) {
            $child = loadFolderTree($fullPath);
            $node->children[$child->name] = $child;
            continue;
        }

        if ($entry->isFile() && strtolower($entry->getExtension()) === 'json') {
            $filename = $entry->getFilename();
            $node->jsonFiles[$filename] = parseJsonFile($fullPath);
        }
    }

    return $node;
}

/**
 * Parse JSON with sane error handling. Returns array/object depending on JSON.
 */
function parseJsonFile(string $path): mixed
{
    $raw = file_get_contents($path);
    if ($raw === false) {
        throw new RuntimeException("Failed to read JSON file: {$path}");
    }

    $data = json_decode($raw, false, 512, JSON_THROW_ON_ERROR);
    $data->wikiPath = substr($path, strlen(__DIR__));

    return $data;
}