<?php

final class TemplateRenderer
{
    private string $templatesDir;
    private string $dataDir;


    public function __construct(?string $templatesDir = null, ?string $dataDir = null)
    {
        $this->dataDir = $dataDir ?? (__DIR__ . DIRECTORY_SEPARATOR . 'data');
        $this->templatesDir = $templatesDir ?? (__DIR__ . DIRECTORY_SEPARATOR . 'templates');
    }

    public function renderFromJsonFile(string $jsonPath): string
    {
        if (!str_contains($jsonPath, __DIR__))
            $jsonPath = __DIR__ . $jsonPath;

        if (!is_file($jsonPath)) {
            throw new RuntimeException("JSON file not found: {$jsonPath}");
        }
        $raw = file_get_contents($jsonPath);
        if ($raw === false) {
            throw new RuntimeException("Failed to read JSON file: {$jsonPath}");
        }
        $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        $data['wikiPath'] = substr($jsonPath, strlen(__DIR__));
        return $this->render($data);
    }

    /**
     * @param array<string, mixed> $data
     */
    public function render(array $data): string
    {
        $type = $data['type'] ?? null;
        if (!is_string($type) || $type === '') {
            throw new RuntimeException("JSON object is missing a valid 'type' field.");
        }

        $template = $this->loadTemplate($type);
        return $this->renderTemplateString($template, $data);
    }

    public function renderAll(array $data): string
    {
        $string = "";
        foreach ($data as $item) {
            $array = json_decode(json_encode($item), true);
            $string .= $this->render($array);
        }

        return $string;
    }

    private function loadTemplate(string $name): string
    {
        $path = $this->templatesDir . DIRECTORY_SEPARATOR . $name . '.template';
        if (!is_file($path)) {
            throw new RuntimeException("Template not found: {$path}");
        }
        $tpl = file_get_contents($path);
        if ($tpl === false) {
            throw new RuntimeException("Failed to read template: {$path}");
        }
        return $tpl;
    }

    /**
     * Main rendering pipeline:
     * 1) resolve child-template tags [[path:tplName]]
     * 2) resolve raw {{{path}}}
     * 3) resolve escaped {{path}}
     * 4) entire lists of a complete folder
     */
    private function renderTemplateString(string $template, array $data): string
    {
        // 1) Child-template tags: [[moves:proficiency.move]]
        $template = preg_replace_callback(
            '/\[\[\s*([a-zA-Z0-9_.-]+)\s*:\s*([a-zA-Z0-9_.-]+)\s*\]\]/',
            function ($m) use ($data) {
                $path = $m[1];
                $childTplName = $m[2];

                $value = $this->getByPath($data, $path);
                if ($value === null)
                    return '';

                $childTpl = $this->loadTemplate($childTplName);

                // Render array => multiple children
                if (is_array($value) && $this->isList($value)) {
                    $out = '';
                    foreach ($value as $childItem) {
                        if (is_array($childItem)) {
                            // Object/assoc child
                            $childCtx = $childItem;
                        } else {
                            // Scalar child (string, int, etc.)
                            $childCtx = [
                                'value' => $childItem
                            ];
                        }

                        $childCtx['_parent'] = $data;
                        $out .= $this->renderTemplateString($childTpl, $childCtx);
                    }
                    return $out;
                }

                // Render object/assoc => single child
                if (is_array($value) && !$this->isList($value)) {
                    $childCtx = $value;
                    $childCtx['_parent'] = $data;
                    return $this->renderTemplateString($childTpl, $childCtx);
                }

                // Scalars: nothing (you could also return scalar string if desired)
                return '';
            },
            $template
        );

        // 2) Raw placeholders {{{path}}}
        $template = preg_replace_callback(
            '/\{\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}\}/',
            fn($m) => $this->toString($this->getByPath($data, $m[1]), false),
            $template
        );

        // 3) Escaped placeholders {{path}}
        $template = preg_replace_callback(
            '/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/',
            fn($m) => $this->toString($this->getByPath($data, $m[1]), true),
            $template
        );

        // 4) [[[entire folders]]]
        $template = preg_replace_callback(
            '/\[\[\[\s*([a-zA-Z0-9_.-]+)\s*\]\]\]/',
            function ($m) use ($data) {
                $folderName = $m[1];

                if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $folderName)) {
                    return '';
                }

                $folderPath = $this->dataDir . DIRECTORY_SEPARATOR . $folderName;

                if (!is_dir($folderPath)) {
                    return '';
                }

                $files = glob($folderPath . DIRECTORY_SEPARATOR . '*.json');
                if ($files === false || count($files) === 0) {
                    return '';
                }

                sort($files, SORT_NATURAL | SORT_FLAG_CASE);

                $out = '';
                foreach ($files as $jsonFile) {
                    try {
                        $out .= $this->renderFromJsonFile($jsonFile);
                    } catch (\Throwable $e) {
                        $out .= '<pre class="renderError">' .
                            htmlspecialchars("Render error in {$jsonFile}: " . $e->getMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') .
                            '</pre>';
                    }
                }

                return $out;
            },
            $template
        );

        // 6) Escaped data-links [data:text:path]
        $template = preg_replace_callback(
            '/\[data:\s*([a-zA-Z0-9_\/.\-><’\'\" ]+)\s*:\s*([a-zA-Z0-9_\/.\-]+)\s*\]/',
            fn($m) => '<a href="?path=/data/' . $m[2] . '">' . $m[1] . '</a>',
            $template
        );

        // 10) scroll links [slink:text:path]
        $template = preg_replace_callback(
            '/\[slink:\s*([a-zA-Z0-9_\/.\->< ]+)\s*:\s*([a-zA-Z0-9_\/., \-]+)\s*\]/',
            fn($m) => '<a class="scrollLink" data-target="' . $m[2] . '">' . $m[1] . '</a>',
            $template
        );

        // 11?) file links [flink:text:path]
        $template = preg_replace_callback(
            '/\[flink:\s*([a-zA-Z0-9_\/.\->< ]+)\s*:\s*([a-zA-Z0-9_\/., \-]+)\s*\]/',
            fn($m) => '<a class="fileLink" href="' . $m[2] . '" download>' . $m[1] . '</a>',
            $template
        );

        // 5) Escaped images [img:path]
        $template = preg_replace_callback(
            '/\[img:\s*([a-zA-Z0-9_\/.\-]+)\s*\]/',
            fn($m) => '<div class="inlineImage"><img src="images/' . $m[1] . '"/></div>',
            $template
        );

        // 7) bold [bold:text]
        $template = preg_replace_callback(
            '/\[bold:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'\+\?=]+)\s*\]/',
            fn($m) => '<b>' . $m[1] . '</b>',
            $template
        );

        // 8) italics [italics:text]
        $template = preg_replace_callback(
            '/\[italics:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
            fn($m) => '<i>' . $m[1] . '</i>',
            $template
        );

        // 9) underline [underline:text]
        $template = preg_replace_callback(
            '/\[underline:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
            fn($m) => '<u>' . $m[1] . '</u>',
            $template
        );

        // 9) header [header:text]
        $template = preg_replace_callback(
            '/\[header:\s*([a-zA-Z0-9_\/.\-<>\s\,\.“”"\'’\+\?=]+)\s*\]/',
            fn($m) => '<h3>' . $m[1] . '</h3>',
            $template
        );

        if (isset($data['wikiPath']))
            $template = str_replace("<<url>>", "?path=" . $data['wikiPath'], $template);

        return $template ?? '';
    }

    private function getByPath(mixed $data, string $path): mixed
    {
        $parts = explode('.', $path);
        $cur = $data;

        foreach ($parts as $part) {
            if (!is_array($cur))
                return null;

            if (ctype_digit($part)) {
                $idx = (int) $part;
                $cur = $cur[$idx] ?? null;
            } else {
                $cur = $cur[$part] ?? null;
            }
        }

        return $cur;
    }

    private function toString(mixed $value, bool $escape): string
    {
        if ($value === null)
            return '';

        if (is_bool($value)) {
            $str = $value ? 'Yes' : 'No';
        } elseif (is_int($value) || is_float($value) || is_string($value)) {
            $str = (string) $value;
        } elseif (is_array($value)) {
            $str = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        } else {
            $str = (string) $value;
        }

        return str_replace("\n", "<br/>", $escape
            ? htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
            : $str);
    }

    private function isList(array $arr): bool
    {
        $i = 0;
        foreach ($arr as $k => $_) {
            if ($k !== $i++)
                return false;
        }
        return true;
    }
}
