<?php

namespace App\Framework\View;

use App\Framework\DI\Container;

/**
 * Erweiterte Version des TemplateProcessors mit DomWrapper-Unterstützung
 */
final readonly class EnhancedTemplateProcessor
{
    public function __construct(
        private array $domProcessors,
        private array $stringProcessors,
        private Container $container
    ) {}

    public function render(RenderContext $context, string $html, bool $component = false): string
    {
        $parser = new DomTemplateParser();
        $domWrapper = $parser->parseToWrapper($html);

        // Verkettete Verarbeitung der DOM-Prozessoren
        foreach ($this->domProcessors as $processorClass) {
            $processor = $this->container->get($processorClass);

            if ($processor instanceof EnhancedDomProcessor) {
                // Verwende die erweiterte DomWrapper-Funktionalität
                $domWrapper = $processor->processWrapper($domWrapper, $context);
            } else {
                // Fallback für bestehende Prozessoren
                $dom = $processor->process($domWrapper->document, $context);
                $domWrapper = new DomWrapper($dom);
            }
        }

        $html = $domWrapper->toHtml($component);

        // Verarbeitung durch String-Prozessoren
        foreach ($this->stringProcessors as $processorClass) {
            $processor = $this->container->get($processorClass);
            $html = $processor->process($html, $context);
        }

        return $html;
    }

    /**
     * Rendert direkt mit DomWrapper für erweiterte Kontrolle
     */
    public function renderWithWrapper(RenderContext $context, string $html, bool $component = false): DomWrapper
    {
        $parser = new DomTemplateParser();
        $domWrapper = $parser->parseToWrapper($html);

        // Verkettete Verarbeitung der DOM-Prozessoren
        foreach ($this->domProcessors as $processorClass) {
            $processor = $this->container->get($processorClass);

            if ($processor instanceof EnhancedDomProcessor) {
                $domWrapper = $processor->processWrapper($domWrapper, $context);
            } else {
                $dom = $processor->process($domWrapper->document, $context);
                $domWrapper = new DomWrapper($dom);
            }
        }

        return $domWrapper;
    }

    public function __debugInfo(): ?array
    {
        return [
            'domProcessors' => $this->domProcessors,
            'stringProcessors' => $this->stringProcessors,
        ];
    }
}
