<?php declare(strict_types=1);

namespace App\Engine\Templating;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Twig\TwigFilter;

class ViteExtension extends AbstractExtension
{

    public function __construct(
        private readonly string                                        $rootDir,
        private readonly \Symfony\Component\HttpKernel\KernelInterface $kernel,
        private readonly string                                        $appVueViteUrl,
    ) {
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('viteHead', $this->viteEntryPoint(...), ['is_safe' => ['html']]),
        ];
    }

    public function viteEntryPoint(string $entry): string
    {
        $manifest = json_decode(file_get_contents($this->rootDir . '/public/build/manifest.json'), true);

        if (!isset($manifest[$entry])) {
            throw new \Exception(sprintf('Asset "%s" not found in Vite manifest.', $entry));
        }

        $tags = [];

        // Vite client
        if ($this->kernel->getEnvironment() === 'dev') {
            $host = rtrim($this->appVueViteUrl, '/');

            $tags[] = sprintf('<script type="module" src="%s/@vite/client"></script>', $host); // HMR client
            $tags[] = sprintf('<script type="module" src="%s/%s"></script>', $host, $manifest[$entry]['src']);
        } else {
            // CSS files
            if (isset($manifest[$entry]['css'])) {
                foreach ($manifest[$entry]['css'] as $css) {
                    $tags[] = sprintf('<link rel="stylesheet" href="/build/%s">', $css);
                }
            }

            $tags[] = sprintf('<script type="module" src="/build/%s"></script>', $manifest[$entry]['file']);
        }

        return implode("\n", $tags);
    }

}
