<?php

declare(strict_types=1);

namespace App\Framework\View;

use App\Framework\Filesystem\FileStorage;
use App\Framework\Meta\MetaData;
use App\Framework\View\Loading\TemplateLoader;

final readonly class ComponentRenderer
{
    public function __construct(
        private TemplateProcessor $processor,
        private ComponentCache $cache,
        private TemplateLoader    $loader,
        private FileStorage       $storage = new FileStorage('/'),
    ) {
    }

    public function render(string $componentName, array $data): string
    {
        $path = $this->loader->getComponentPath($componentName);

        if (! $this->storage->exists($path)) {
            return "<!-- Komponente '$componentName' nicht gefunden -->";
        }

        if ($cached = $this->cache->get($componentName, $data, $path)) {
            return $cached;
        }

        $template = $this->storage->get($path);
        $context = new RenderContext(template: $componentName, metaData: new MetaData(''), data: $data);

        file_put_contents('/tmp/debug.log', "ComponentRenderer::render - Component: $componentName, Template length: " . strlen($template) . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "ComponentRenderer::render - Template starts with: " . substr($template, 0, 100) . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "ComponentRenderer::render - Data keys: " . implode(', ', array_keys($data)) . "\n", FILE_APPEND | LOCK_EX);
        if (isset($data['bodyContent'])) {
            file_put_contents('/tmp/debug.log', "ComponentRenderer::render - bodyContent length: " . strlen($data['bodyContent']) . "\n", FILE_APPEND | LOCK_EX);
            file_put_contents('/tmp/debug.log', "ComponentRenderer::render - bodyContent starts: " . substr($data['bodyContent'], 0, 200) . "\n", FILE_APPEND | LOCK_EX);
        }
        file_put_contents('/tmp/debug.log', "ComponentRenderer::render - About to call processor->render (component=true)\n", FILE_APPEND | LOCK_EX);

        $output = $this->processor->render($context, $template, true);

        // Ensure we never return null
        if ($output === null) {
            $output = '';
        }

        $this->cache->set($componentName, $data, $path, $output);

        return $output;
    }
}
