<?php

declare(strict_types=1);

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

use App\Framework\QrCode\DataEncoder;
use App\Framework\QrCode\DataMode;
use App\Framework\QrCode\ErrorCorrectionLevel;
use App\Framework\QrCode\QrCodeVersion;

// Debug capacity calculation
$testData = 'otpauth://totp/Test?secret=JBSWY3DPEHPK3PXP';
echo "Testing data: $testData\n";
echo "Length: " . strlen($testData) . " characters\n\n";

// Test different versions
for ($versionNum = 1; $versionNum <= 6; $versionNum++) {
    $version = new QrCodeVersion($versionNum);

    echo "=== Version $versionNum (Size: " . $version->getModuleCount() . "x" . $version->getModuleCount() . ") ===\n";

    foreach ([ErrorCorrectionLevel::L, ErrorCorrectionLevel::M, ErrorCorrectionLevel::Q, ErrorCorrectionLevel::H] as $errorLevel) {
        $capacity = $version->getDataCapacity($errorLevel);
        echo "  {$errorLevel->value}: $capacity bits (" . ($capacity / 8) . " bytes)\n";
    }
    echo "\n";
}

// Manual encoding test
echo "=== Manual Encoding Analysis ===\n";
$mode = DataMode::detectForData($testData);
echo "Detected mode: {$mode->value}\n";

$encoder = new DataEncoder();
$version = new QrCodeVersion(3);
$errorLevel = ErrorCorrectionLevel::L;

echo "\nStep-by-step encoding for Version 3, Level L:\n";
echo "Capacity: " . $version->getDataCapacity($errorLevel) . " bits\n";

// Manual bit calculation
$modeIndicator = 4; // 4 bits for byte mode
$characterCount = 8; // Version 1-9: 8 bits for character count in byte mode
$dataLength = strlen($testData) * 8; // Each byte = 8 bits
$terminator = 4; // Up to 4 terminator bits
$paddingToByte = 7; // Up to 7 bits to pad to byte boundary

$totalBits = $modeIndicator + $characterCount + $dataLength + $terminator + $paddingToByte;
echo "Manual calculation:\n";
echo "  Mode indicator: $modeIndicator bits\n";
echo "  Character count: $characterCount bits\n";
echo "  Data payload: $dataLength bits (" . strlen($testData) . " chars × 8 bits)\n";
echo "  Terminator: $terminator bits (max)\n";
echo "  Byte padding: $paddingToByte bits (max)\n";
echo "  Total (worst case): $totalBits bits\n";
echo "  Actual needed: ~" . ($modeIndicator + $characterCount + $dataLength + 4) . " bits\n";

$actualCapacity = $version->getDataCapacity($errorLevel);
echo "  Available capacity: $actualCapacity bits\n";
echo "  Should fit: " . ($actualCapacity >= ($modeIndicator + $characterCount + $dataLength + 4) ? "YES" : "NO") . "\n";
