<?php

declare(strict_types=1);

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

use App\Framework\QrCode\QrCodeGenerator;

echo "🧪 Testing QR Code Generator...\n\n";

try {
    // Create QR Code Generator
    $generator = QrCodeGenerator::create();

    // Test data
    $testData = "Hello World!";
    echo "📝 Test Data: {$testData}\n";

    // Analyze the data
    $analysis = $generator->analyzeData($testData);
    echo "📊 Data Analysis:\n";
    foreach ($analysis as $key => $value) {
        echo "   {$key}: " . (is_object($value) ? $value::class : $value) . "\n";
    }
    echo "\n";

    // Generate QR Code Matrix
    echo "🏗️  Generating QR Code Matrix...\n";
    $matrix = $generator->generateMatrix($testData);

    echo "📏 Matrix Size: {$matrix->getSize()}x{$matrix->getSize()}\n";

    $stats = $matrix->getStatistics();
    echo "📊 Matrix Statistics:\n";
    foreach ($stats as $key => $value) {
        echo "   {$key}: {$value}\n";
    }
    echo "\n";

    // Generate ASCII representation for terminal
    echo "🎨 ASCII QR Code (for terminal):\n";
    echo $matrix->toString('██', '  ') . "\n";

    // Generate SVG
    echo "🖼️  Generating SVG...\n";
    $svg = $generator->generateSvg($testData);

    // Save SVG to file
    $svgFile = __DIR__ . '/test-qr-code.svg';
    file_put_contents($svgFile, $svg);
    echo "💾 SVG saved to: {$svgFile}\n";

    // Generate Data URI
    $dataUri = $generator->generateDataUri($testData);
    echo "🔗 Data URI length: " . strlen($dataUri) . " characters\n";
    echo "🔗 Data URI preview: " . substr($dataUri, 0, 100) . "...\n\n";

    // Test TOTP URI
    echo "🔐 Testing TOTP QR Code...\n";
    $totpUri = 'otpauth://totp/Test:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Test&algorithm=SHA1&digits=6&period=30';
    echo "📝 TOTP URI: {$totpUri}\n";
    echo "📏 TOTP URI Length: " . strlen($totpUri) . " bytes\n";

    // Analyze TOTP data
    $totpAnalysis = $generator->analyzeData($totpUri);
    echo "📊 TOTP Analysis:\n";
    foreach ($totpAnalysis as $key => $value) {
        echo "   {$key}: " . (is_object($value) ? $value::class : $value) . "\n";
    }
    echo "\n";

    // Force version 3 for TOTP (2208 bits capacity)
    $totpSvg = $generator->generateSvg($totpUri, \App\Framework\QrCode\ErrorCorrectionLevel::M, new \App\Framework\QrCode\QrCodeVersion(3));
    $totpFile = __DIR__ . '/test-totp-qr.svg';
    file_put_contents($totpFile, $totpSvg);
    echo "💾 TOTP QR Code saved to: {$totpFile}\n";

    echo "\n✅ QR Code generation successful!\n";
    echo "🌐 You can open the SVG files in your browser to see the QR codes.\n";

} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    echo "📍 File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "🔍 Trace:\n" . $e->getTraceAsString() . "\n";
}
