<?php

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\LiveComponents\Contracts\ComponentRegistryInterface;
use App\Framework\View\Contracts\HtmlComponentRegistryInterface;
use App\Framework\LiveComponents\Performance\ComponentMetadataCacheInterface;
use App\Framework\Template\Parser\DomTemplateParser;
use App\Framework\View\DomComponentService;
use App\Framework\View\Processors\XComponentProcessor;
use App\Framework\View\RenderContext;
use App\Framework\Meta\MetaData;

// Mock with logging
$liveComponentRegistry = Mockery::mock(ComponentRegistryInterface::class);
$htmlComponentRegistry = Mockery::mock(HtmlComponentRegistryInterface::class);
$metadataCache = Mockery::mock(ComponentMetadataCacheInterface::class);

// Add logging to see what methods are called
$liveComponentRegistry->shouldReceive('isRegistered')
    ->andReturnUsing(function ($name) {
        echo "Mock called: isRegistered('$name')\n";
        return $name === 'counter';
    });

$liveComponentRegistry->shouldReceive('getClassName')
    ->andReturnUsing(function ($name) {
        echo "Mock called: getClassName('$name')\n";
        return 'TestCounter';
    });

$liveComponentRegistry->shouldReceive('resolve')
    ->andReturnUsing(function () {
        echo "Mock called: resolve(...)\n";
        throw new \Exception("Unexpected call to resolve");
    });

$htmlComponentRegistry->shouldReceive('has')
    ->andReturnUsing(function ($name) {
        echo "Mock called: htmlComponentRegistry->has('$name')\n";
        return false;
    });

$processor = new XComponentProcessor(
    $liveComponentRegistry,
    $htmlComponentRegistry,
    $metadataCache,
    new DomComponentService()
);

$html = '<html><body><x-counter id="demo" /></body></html>';
echo "Input: $html\n\n";

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

echo "Parsed: " . $dom->document->saveHTML() . "\n\n";

$context = new RenderContext(
    template: 'test',
    metaData: new MetaData('Test'),
    data: []
);

echo "Processing...\n";
try {
    $result = $processor->process($dom, $context);
    echo "Result: " . $result->document->saveHTML() . "\n";
} catch (\Throwable $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
}
