<?php

declare(strict_types=1);

/**
 * Test für Framework-konforme Template Exception Handling
 */

require_once __DIR__ . '/../bootstrap.php';

use App\Framework\Exception\ErrorCode;
use App\Framework\Exception\FrameworkException;
use App\Framework\View\Exceptions\TemplateCacheException;
use App\Framework\View\Exceptions\TemplateNotFoundException;
use App\Framework\View\Exceptions\TemplateProcessorException;
use App\Framework\View\Exceptions\TemplateRenderingException;

try {
    echo "🧪 Testing Template Exception Handling Framework Integration\n";
    echo "=" . str_repeat("=", 60) . "\n\n";

    // Test 1: TemplateNotFoundException Factory Methods
    echo "🔍 Test 1: TemplateNotFoundException Factory Methods\n";
    echo "-" . str_repeat("-", 45) . "\n";

    $exception = TemplateNotFoundException::forTemplate(
        'user/profile',
        '/app/templates',
        ['/app/templates', '/app/views']
    );

    echo "Exception Class: " . get_class($exception) . "\n";
    echo "Error Code: " . $exception->getErrorCode()->value . " (" . $exception->getErrorCode()->getDescription() . ")\n";
    echo "Message: " . $exception->getMessage() . "\n";
    echo "Operation: " . $exception->getContext()->operation . "\n";
    echo "Component: " . $exception->getContext()->component . "\n";
    echo "Template: " . $exception->getContext()->data['template'] . "\n";
    echo "Suggestions: " . json_encode($exception->getContext()->metadata['suggestions']) . "\n";
    echo "Template Type: " . $exception->getContext()->metadata['template_type'] . "\n\n";

    // Test 2: TemplateCacheException
    echo "🔍 Test 2: TemplateCacheException Error Codes\n";
    echo "-" . str_repeat("-", 45) . "\n";

    $cacheException = TemplateCacheException::cacheWriteFailed(
        'template_user_profile_123',
        '/tmp/cache/templates/user_profile_123.cache'
    );

    echo "Exception Class: " . get_class($cacheException) . "\n";
    echo "Error Code: " . $cacheException->getErrorCode()->value . "\n";
    echo "Description: " . $cacheException->getErrorCode()->getDescription() . "\n";
    echo "Recovery Hint: " . $cacheException->getErrorCode()->getRecoveryHint() . "\n";
    echo "Is Recoverable: " . ($cacheException->getErrorCode()->isRecoverable() ? 'Yes' : 'No') . "\n";
    echo "Retry After: " . ($cacheException->getErrorCode()->getRetryAfterSeconds() ?? 'N/A') . " seconds\n";
    echo "Recovery Strategy: " . $cacheException->getContext()->metadata['recovery_strategy'] . "\n\n";

    // Test 3: TemplateRenderingException Variable Resolution
    echo "🔍 Test 3: TemplateRenderingException Variable Resolution\n";
    echo "-" . str_repeat("-", 45) . "\n";

    $renderingException = TemplateRenderingException::variableNotFound(
        'user/dashboard',
        'userName',
        ['user' => ['id' => 1], 'userProfile' => ['name' => 'John'], 'userSettings' => []]
    );

    echo "Exception Class: " . get_class($renderingException) . "\n";
    echo "Error Code: " . $renderingException->getErrorCode()->value . "\n";
    echo "Missing Variable: " . $renderingException->getContext()->data['missing_variable'] . "\n";
    echo "Available Variables: " . json_encode($renderingException->getContext()->data['available_variables']) . "\n";
    echo "Suggestions: " . json_encode($renderingException->getContext()->metadata['suggestions']) . "\n\n";

    // Test 4: TemplateProcessorException Chain Failure
    echo "🔍 Test 4: TemplateProcessorException Chain Failure\n";
    echo "-" . str_repeat("-", 45) . "\n";

    $processorException = TemplateProcessorException::processorChainFailed(
        ['AssetInjector', 'FormProcessor', 'LayoutProcessor', 'ComponentProcessor'],
        'FormProcessor'
    );

    echo "Exception Class: " . get_class($processorException) . "\n";
    echo "Error Code: " . $processorException->getErrorCode()->value . "\n";
    echo "Failed Processor: " . $processorException->getContext()->data['failed_processor'] . "\n";
    echo "Chain Position: " . $processorException->getContext()->data['chain_position'] . "\n";
    echo "Recovery Strategy: " . $processorException->getContext()->metadata['recovery_strategy'] . "\n\n";

    // Test 5: ErrorCode Template Categories
    echo "🔍 Test 5: ErrorCode Template Categories\n";
    echo "-" . str_repeat("-", 45) . "\n";

    $templateErrorCodes = [
        ErrorCode::TPL_TEMPLATE_NOT_FOUND,
        ErrorCode::TPL_SYNTAX_ERROR,
        ErrorCode::TPL_VARIABLE_NOT_FOUND,
        ErrorCode::TPL_COMPILATION_FAILED,
        ErrorCode::TPL_RENDERING_FAILED,
        ErrorCode::TPL_CACHE_FAILED,
        ErrorCode::TPL_CONTENT_LOADING_FAILED,
        ErrorCode::TPL_PROCESSOR_FAILED,
        ErrorCode::TPL_ASSET_NOT_FOUND,
        ErrorCode::TPL_INVALID_TEMPLATE_TYPE,
    ];

    foreach ($templateErrorCodes as $errorCode) {
        $category = $errorCode->getCategory();
        $isRecoverable = $errorCode->isRecoverable() ? 'Yes' : 'No';
        $retryAfter = $errorCode->getRetryAfterSeconds() ?? 'N/A';

        echo "  {$errorCode->value}: {$errorCode->getDescription()}\n";
        echo "    Category: $category | Recoverable: $isRecoverable | Retry: $retryAfter\n";
    }
    echo "\n";

    // Test 6: Framework Exception Hierarchy Compliance
    echo "🔍 Test 6: Framework Exception Hierarchy Compliance\n";
    echo "-" . str_repeat("-", 45) . "\n";

    $exceptions = [
        'TemplateNotFoundException' => TemplateNotFoundException::forTemplate('test'),
        'TemplateCacheException' => TemplateCacheException::cacheReadFailed('test', '/tmp/test'),
        'TemplateRenderingException' => TemplateRenderingException::renderingFailed('test', 'processing'),
        'TemplateProcessorException' => TemplateProcessorException::processorFailed('TestProcessor', 'test', 'operation'),
    ];

    foreach ($exceptions as $name => $exception) {
        $isFrameworkException = $exception instanceof FrameworkException;
        $hasErrorCode = $exception->getErrorCode() !== null;
        $hasContext = $exception->getContext() !== null;
        $isFinal = (new ReflectionClass($exception))->isFinal();

        echo "  $name:\n";
        echo "    ✅ Framework Exception: " . ($isFrameworkException ? 'Yes' : 'No') . "\n";
        echo "    ✅ Has ErrorCode: " . ($hasErrorCode ? 'Yes' : 'No') . "\n";
        echo "    ✅ Has Context: " . ($hasContext ? 'Yes' : 'No') . "\n";
        echo "    ✅ Is Final: " . ($isFinal ? 'Yes' : 'No') . "\n";
    }

    echo "\n🎉 All Template Exception Handling Tests completed successfully!\n\n";

    echo "📋 Summary of Framework Integration:\n";
    echo "   ✅ Modern FrameworkException mit ErrorCode Integration\n";
    echo "   ✅ Rich Exception Context mit Operation/Component Tracking\n";
    echo "   ✅ Factory Methods für konsistente Exception Creation\n";
    echo "   ✅ Recovery Hints und Retry Strategies\n";
    echo "   ✅ Template-spezifische Error Codes (TPL001-TPL010)\n";
    echo "   ✅ Intelligent Error Suggestions und Metadata\n";
    echo "   ✅ Framework-konforme final readonly Classes\n";
    echo "   ✅ Backward Compatible Legacy Support\n";

} catch (Exception $e) {
    echo "❌ Test failed with error: " . $e->getMessage() . "\n";
    echo "Exception: " . get_class($e) . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
