<?php

declare(strict_types=1);

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

use App\Framework\ErrorHandling\DummyTemplateRenderer;
use App\Framework\ErrorHandling\View\ErrorTemplateRenderer;
use App\Framework\Exception\ErrorHandlerContext;
use App\Framework\Exception\ExceptionContext;
use App\Framework\Exception\RequestContext;
use App\Framework\Exception\SystemContext;
use App\Framework\Http\RequestId;
use App\Framework\UserAgent\UserAgent;

// Erstelle eine Test-Exception
$testException = new \RuntimeException('Test error for enhanced debug page', 500);

// Erstelle ErrorHandlerContext mit Test-Daten
$exceptionContext = ExceptionContext::empty()
    ->withOperation('test_operation', 'TestComponent')
    ->withData([
        'exception_message' => $testException->getMessage(),
        'exception_file' => $testException->getFile(),
        'exception_line' => $testException->getLine(),
        'original_exception' => $testException,
    ]);

$requestContext = RequestContext::create(
    clientIp: '127.0.0.1',
    userAgent: UserAgent::fromString('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'),
    requestMethod: 'GET',
    requestUri: '/test-error',
    hostIp: '127.0.0.1',
    hostname: 'localhost',
    protocol: 'HTTP/1.1',
    port: '80',
    requestId: new RequestId()
);

$systemContext = new SystemContext(
    memoryUsage: '25 MB',
    executionTime: 0.25, // 250ms
    phpVersion: PHP_VERSION,
    frameworkVersion: '1.0.0-dev',
    environment: ['test_system_data' => 'value']
);

$metadata = [
    'exception_class' => get_class($testException),
    'error_level' => 'ERROR',
    'http_status' => 500,
];

$errorHandlerContext = ErrorHandlerContext::create(
    $exceptionContext,
    $requestContext,
    $systemContext,
    $metadata
);

// Erstelle Template Renderer
$templateRenderer = new DummyTemplateRenderer();

// Erstelle Error Template Renderer
$errorRenderer = new ErrorTemplateRenderer($templateRenderer);

// Rendere die Enhanced Debug Page
try {
    $html = $errorRenderer->renderFromHandlerContext($errorHandlerContext, true);

    // Speichere in temporäre Datei zum Betrachten im Browser
    $outputFile = __DIR__ . '/../tmp/enhanced-error-page-test.html';
    file_put_contents($outputFile, $html);

    echo "✅ Enhanced Error Page erfolgreich gerendert!\n";
    echo "📁 Gespeichert in: {$outputFile}\n";
    echo "🌐 Öffne die Datei im Browser, um das Ergebnis zu sehen.\n";
    echo "\nHTML Länge: " . strlen($html) . " Zeichen\n";

} catch (\Throwable $e) {
    echo "❌ Fehler beim Rendern der Enhanced Error Page:\n";
    echo "Fehler: " . $e->getMessage() . "\n";
    echo "Datei: " . $e->getFile() . "\n";
    echo "Zeile: " . $e->getLine() . "\n";
    echo "\nStack Trace:\n" . $e->getTraceAsString() . "\n";
}
