<?php

declare(strict_types=1);

namespace App\Framework\View\Processing;

use App\Framework\Template\Parser\DomTemplateParser;
use App\Framework\Template\Processing\DomProcessor;
use App\Framework\Template\Processing\ProcessorResolver;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;

final readonly class DomProcessingPipeline
{
    /** @param class-string[] $processors */
    public function __construct(
        private array             $processors,
        private ProcessorResolver $resolver,
    ) {
    }

    public function process(RenderContext $context, string $html): DomWrapper
    {
        file_put_contents('/tmp/debug.log', "DomProcessingPipeline::process ENTRY - Template: " . $context->template . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "DomProcessingPipeline::process ENTRY - HTML length: " . strlen($html) . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "DomProcessingPipeline::process ENTRY - HTML starts with: " . substr($html, 0, 200) . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "DomProcessingPipeline::process ENTRY - HTML contains '<component': " . (strpos($html, '<component') !== false ? 'YES' : 'NO') . "\n", FILE_APPEND | LOCK_EX);

        $parser = new DomTemplateParser();
        $dom = $parser->parseToWrapper($html);

        foreach ($this->processors as $processorClass) {
            try {
                file_put_contents('/tmp/debug.log', "DomProcessingPipeline: Processing with " . $processorClass . "\n", FILE_APPEND | LOCK_EX);
                /** @var DomProcessor $processor */
                $processor = $this->resolver->resolve($processorClass);
                file_put_contents('/tmp/debug.log', "DomProcessingPipeline: Successfully resolved " . $processorClass . "\n", FILE_APPEND | LOCK_EX);

                $dom = $processor->process($dom, $context);
                file_put_contents('/tmp/debug.log', "DomProcessingPipeline: Completed processing with " . $processorClass . "\n", FILE_APPEND | LOCK_EX);
            } catch (\Throwable $e) {
                file_put_contents('/tmp/debug.log', "DomProcessingPipeline: ERROR processing " . $processorClass . ": " . $e->getMessage() . "\n", FILE_APPEND | LOCK_EX);
                file_put_contents('/tmp/debug.log', "DomProcessingPipeline: Stack trace: " . $e->getTraceAsString() . "\n", FILE_APPEND | LOCK_EX);

                throw $e;
            }
        }

        file_put_contents('/tmp/debug.log', "DomProcessingPipeline: ALL PROCESSORS COMPLETED SUCCESSFULLY\n", FILE_APPEND | LOCK_EX);

        return $dom;
    }
}
