<?php

namespace App\Framework\View\Processors;

use App\Framework\Core\PathProvider;
use App\Framework\View\DomHeadService;
use App\Framework\View\DomProcessor;
use App\Framework\View\DomWrapper;
use Dom\HTMLDocument;
use DOMDocument;
use DOMElement;
use App\Framework\View\RenderContext;

final class AssetInjector implements DomProcessor
{
    private array $manifest;

    public function __construct(
        PathProvider $pathProvider,
        private DomHeadService $headService,
        string $manifestPath = '',
    )
    {

        $manifestPath = $pathProvider->resolvePath('/public/.vite/manifest.json');;

        #$manifestPath = dirname(__DIR__, 3) . '../public/.vite/manifest.json';


        if (!is_file($manifestPath)) {
            throw new \RuntimeException("Vite manifest not found: $manifestPath");
        }
        $json = file_get_contents($manifestPath);

        $this->manifest = json_decode($json, true) ?? [];
    }

    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        // JS-Key, wie im Manifest unter "resources/js/main.js"
        $jsKey = 'resources/js/main.js';
        // CSS-Key, wie im Manifest unter "resources/css/styles.css"
        $cssKey = 'resources/css/styles.css';

        #$head = $dom->getElementsByTagName('head')->item(0);
        $head = $dom->document->head;
        $insertParent = $head ?: $dom->document->getElementsByTagName('body')->item(0) ?: $dom->document->documentElement;

        // --- CSS, wie von Vite empfohlen: Feld "css" beim js-Eintrag! ---
        if (!empty($this->manifest[$jsKey]['css']) && is_array($this->manifest[$jsKey]['css'])) {
            foreach ($this->manifest[$jsKey]['css'] as $cssFile) {

                $this->headService->addStylesheet($dom, '/' . ltrim($cssFile, '/'));

                /*$link = $dom->document->createElement('link');
                $link->setAttribute('rel', 'stylesheet');
                $link->setAttribute('href', '/' . ltrim($cssFile, '/'));
                $insertParent->appendChild($link);*/
            }
        }

        // --- JS Main Script ---
        if (isset($this->manifest[$jsKey]['file']) && str_ends_with($this->manifest[$jsKey]['file'], '.js')) {

            $this->headService->addScript($dom, '/' . ltrim($this->manifest[$jsKey]['file'], '/'));
            /*$script = $dom->document->createElement('script');
            $script->setAttribute('src', '/' . ltrim($this->manifest[$jsKey]['file'], '/'));
            $script->setAttribute('type', 'module');
            $insertParent->appendChild($script);*/
        }

        return $dom;
    }
}
