<?php

final class TemplateRenderer
{
    private string $templatesDir;

    public function __construct(?string $templatesDir = null)
    {
        $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}}
     */
    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
        );

        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 ? 'true' : 'false';
        } 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
    {
        // PHP 8.1+: array_is_list($arr)
        $i = 0;
        foreach ($arr as $k => $_) {
            if ($k !== $i++)
                return false;
        }
        return true;
    }
}
