<?php

declare(strict_types=1);

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

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

// Simulate DataEncoder steps manually
$testData = 'otpauth://totp/Test?secret=JBSWY3DPEHPK3PXP';
$version = new QrCodeVersion(3);
$errorLevel = ErrorCorrectionLevel::L;

echo "=== Bit Calculation Debug ===\n";
echo "Data: '$testData'\n";
echo "Length: " . strlen($testData) . " characters\n";
echo "Version: " . $version->getVersion() . "\n";
echo "Error Level: {$errorLevel->value}\n";
echo "Available capacity: " . $version->getDataCapacity($errorLevel) . " bits\n\n";

// Step 1: Mode detection
$mode = DataMode::detectForData($testData);
echo "Detected mode: {$mode->value}\n";

// Step 2: Mode indicator (4 bits)
$modeIndicator = match($mode) {
    DataMode::NUMERIC => '0001',
    DataMode::ALPHANUMERIC => '0010',
    DataMode::BYTE => '0100',
    DataMode::KANJI => '1000',
};
echo "Mode indicator: '$modeIndicator' (" . strlen($modeIndicator) . " bits)\n";

// Step 3: Character count indicator
// For byte mode, versions 1-9: 8 bits
$characterCount = str_pad(decbin(strlen($testData)), 8, '0', STR_PAD_LEFT);
echo "Character count: '$characterCount' (" . strlen($characterCount) . " bits) - represents " . strlen($testData) . " chars\n";

// Step 4: Data encoding (byte mode = 8 bits per char)
$dataEncoding = '';
for ($i = 0; $i < strlen($testData); $i++) {
    $byte = ord($testData[$i]);
    $dataEncoding .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
}
echo "Data encoding: " . strlen($dataEncoding) . " bits (" . strlen($testData) . " chars × 8 bits)\n";

// Current total
$currentTotal = strlen($modeIndicator) + strlen($characterCount) + strlen($dataEncoding);
echo "\nRunning total: $currentTotal bits\n";

// Step 5: Terminator (up to 4 bits)
$capacity = $version->getDataCapacity($errorLevel);
$terminatorBits = min(4, $capacity - $currentTotal);
echo "Terminator bits to add: $terminatorBits\n";
$currentTotal += $terminatorBits;

// Step 6: Pad to byte boundary
$bytePadding = (8 - ($currentTotal % 8)) % 8;
echo "Byte padding needed: $bytePadding bits\n";
$currentTotal += $bytePadding;

echo "\nFinal total before codeword padding: $currentTotal bits\n";
echo "Available capacity: $capacity bits\n";
echo "Fits: " . ($currentTotal <= $capacity ? 'YES' : 'NO') . "\n";

// The discrepancy test
if ($currentTotal > $capacity) {
    echo "\n⚠️  ERROR: This should not happen - basic encoding exceeds capacity!\n";
    echo "Something is wrong with our calculation or the actual DataEncoder.\n";
} else {
    echo "\n✅ Basic encoding fits. Problem must be elsewhere.\n";
}
