<?php

declare(strict_types=1);

namespace App\Framework\View\Processors;

use App\Framework\DI\Container;
use App\Framework\Template\Processing\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;

final readonly class ForDomProcessor implements DomProcessor
{
    public function __construct(
        private Container $container,
        private ForStringProcessor $stringProcessor
    ) {
    }

    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        error_log("🔧 ForDomProcessor: Processing DOM for final <for> tag cleanup");

        // Get the complete HTML content as string
        $htmlContent = $dom->document->saveHTML();

        error_log("🔧 ForDomProcessor: Content contains '<for': " . (strpos($htmlContent, '<for') !== false ? 'YES' : 'NO'));
        error_log("🔧 ForDomProcessor: Content contains 'health_checks': " . (strpos($htmlContent, 'health_checks') !== false ? 'YES' : 'NO'));

        // If we have <for> tags, process the entire HTML string before DOM parsing touches it
        if (strpos($htmlContent, '<for') !== false) {
            error_log("🔧 ForDomProcessor: Found <for> tags, processing entire HTML string");

            // Process the entire HTML content with string processor
            $processedHtmlContent = $this->stringProcessor->process($htmlContent, $context);

            error_log("🔧 ForDomProcessor: HTML processing complete, result contains '<for': " . (strpos($processedHtmlContent, '<for') !== false ? 'YES' : 'NO'));

            // Parse the processed HTML back into DOM
            if ($processedHtmlContent !== $htmlContent) {
                error_log("🔧 ForDomProcessor: HTML was modified, updating body content");

                // Find the body and replace its content with the processed content
                $body = $dom->document->querySelector('body');
                if ($body) {
                    // Extract just the body content from the processed HTML
                    if (preg_match('/<body[^>]*>(.*?)<\/body>/s', $processedHtmlContent, $matches)) {
                        $body->innerHTML = $matches[1];
                        error_log("🔧 ForDomProcessor: Body content updated with processed HTML");
                    }
                }
            }
        }

        return $dom;
    }
}
