<?php

declare(strict_types=1);

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

use App\Framework\LiveComponents\Contracts\ComponentRegistryInterface;
use App\Framework\LiveComponents\Contracts\LiveComponentContract;
use App\Framework\LiveComponents\Performance\ComponentMetadataCacheInterface;
use App\Framework\LiveComponents\Performance\CompiledComponentMetadata;
use App\Framework\LiveComponents\Performance\ComponentPropertyMetadata;
use App\Framework\LiveComponents\ValueObjects\ComponentData;
use App\Framework\LiveComponents\ValueObjects\ComponentId;
use App\Framework\LiveComponents\ValueObjects\ComponentRenderData;
use App\Framework\View\Contracts\HtmlComponentRegistryInterface;
use App\Framework\View\DomComponentService;
use App\Framework\View\Processors\XComponentProcessor;
use App\Framework\View\RenderContext;
use App\Framework\Template\Parser\DomTemplateParser;
use App\Framework\Meta\MetaData;

echo "=== Test Validation Issue ===\n\n";

// Set development mode to see error messages
$_ENV['APP_ENV'] = 'development';
echo "APP_ENV set to: " . ($_ENV['APP_ENV'] ?? 'not set') . "\n\n";

// Create simple mocks
$liveComponentRegistry = new class implements ComponentRegistryInterface {
    public function resolve(ComponentId $componentId, ?ComponentData $state = null): LiveComponentContract
    {
        echo "✓ resolve() WAS CALLED\n";
        return new class implements LiveComponentContract {
            public function getId(): ComponentId { return ComponentId::create('counter', 'demo'); }
            public function getData(): ComponentData { return ComponentData::fromArray([]); }
            public function getRenderData(): ComponentRenderData {
                return new ComponentRenderData('counter-template', []);
            }
        };
    }

    public function render(LiveComponentContract $component): string
    {
        return '<div>Counter</div>';
    }

    public function renderWithWrapper(LiveComponentContract $component): string
    {
        echo "✓ renderWithWrapper() WAS CALLED\n";
        return '<div data-component-id="counter:demo">Counter HTML</div>';
    }

    public function isRegistered(string $componentName): bool
    {
        return $componentName === 'counter';
    }

    public function getClassName(string $componentName): ?string
    {
        return $componentName === 'counter' ? 'TestCounterComponent' : null;
    }

    public function getAllComponentNames(): array
    {
        return ['counter'];
    }
};

$htmlComponentRegistry = new class implements HtmlComponentRegistryInterface {
    public function has(string $componentName): bool
    {
        return false;
    }

    public function render(string $componentName, string $content, array $attributes): string
    {
        return '';
    }

    public function getAllComponentNames(): array
    {
        return [];
    }
};

// This metadata says the component ONLY has 'initialValue' property
$metadataCache = new class implements ComponentMetadataCacheInterface {
    public function get(string $className): CompiledComponentMetadata
    {
        return new CompiledComponentMetadata(
            className: 'TestCounterComponent',
            componentName: 'counter',
            properties: [
                'initialValue' => new ComponentPropertyMetadata(
                    name: 'initialValue',
                    type: 'int',
                    isPublic: true,
                    isReadonly: false
                )
            ],
            actions: [],
            constructorParams: []
        );
    }

    public function has(string $className): bool
    {
        return true;
    }

    public function invalidate(string $className): bool
    {
        return true;
    }

    public function warmCache(array $classNames): int
    {
        return 0;
    }
};

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

$parser = new DomTemplateParser();

// Test 1: HTML with id attribute (should be accepted, 'id' is skipped in validation)
echo "=== Test 1: With 'id' attribute (should work) ===\n";
$html1 = '<html><body><x-counter id="demo" initialValue="5" /></body></html>';
$dom1 = $parser->parseToWrapper($html1);
$context = new RenderContext(
    template: 'test',
    metaData: new MetaData('test'),
    data: []
);

$result1 = $processor->process($dom1, $context);
$resultHtml1 = $result1->document->saveHTML();
echo "Result HTML: {$resultHtml1}\n";

if (str_contains($resultHtml1, 'data-component-id')) {
    echo "✅ SUCCESS\n";
} else {
    echo "❌ FAILURE\n";
    if (str_contains($resultHtml1, 'XComponentProcessor Error')) {
        echo "Error message found in HTML\n";
    }
}
echo "\n";

// Test 2: HTML WITHOUT id attribute (should generate auto-id)
echo "=== Test 2: Without 'id' attribute (should work) ===\n";
$html2 = '<html><body><x-counter initialValue="0" /></body></html>';
$dom2 = $parser->parseToWrapper($html2);

$result2 = $processor->process($dom2, $context);
$resultHtml2 = $result2->document->saveHTML();
echo "Result HTML: {$resultHtml2}\n";

if (str_contains($resultHtml2, 'data-component-id')) {
    echo "✅ SUCCESS\n";
} else {
    echo "❌ FAILURE\n";
    if (str_contains($resultHtml2, 'XComponentProcessor Error')) {
        echo "Error message found in HTML\n";
    }
}
