<?php

/**
 * Format unused translation keys from the table output
 */

$file = '/tmp/unused-keys-table.txt';
$content = file_get_contents($file);
$lines = explode("\n", $content);

$keys = [];
$inTable = false;

foreach ($lines as $line) {
    // Skip header lines and decorations
    if (strpos($line, 'Translation Key') !== false) {
        $inTable = true;
        continue;
    }

    if (!$inTable) continue;

    // Extract key and value from table format
    if (preg_match('/^\|\s+([a-z][^\|]+?)\s+\|\s+(.+?)\s+\|$/i', $line, $matches)) {
        $key = trim($matches[1]);
        $value = trim($matches[2]);

        // Skip divider lines
        if (strpos($key, '---') !== false || strpos($key, '===') !== false) continue;

        $keys[$key] = $value;
    }
}

echo "=== UNUSED TRANSLATION KEYS ===\n";
echo "Total found: " . count($keys) . " keys\n";
echo str_repeat('=', 100) . "\n\n";

// Group by prefix
$grouped = [];
foreach ($keys as $key => $value) {
    $parts = explode('.', $key);
    $prefix = $parts[0];

    if (!isset($grouped[$prefix])) {
        $grouped[$prefix] = [];
    }
    $grouped[$prefix][$key] = $value;
}

ksort($grouped);

// Display each group
foreach ($grouped as $prefix => $items) {
    echo "\n" . strtoupper($prefix) . " (" . count($items) . " keys)\n";
    echo str_repeat('-', 100) . "\n";

    foreach ($items as $key => $value) {
        // Truncate very long values
        if (strlen($value) > 70) {
            $value = substr($value, 0, 67) . '...';
        }
        printf("  %-50s → %s\n", $key, $value);
    }
}

echo "\n" . str_repeat('=', 100) . "\n";
echo "TOTAL: " . count($keys) . " unused translation keys\n\n";

echo "NOTE: Some keys may be used dynamically (e.g., __(\$variable)).\n";
echo "Review carefully before deleting.\n\n";

// Save clean list for user reference
$cleanList = array_keys($keys);
file_put_contents('/tmp/unused-keys-clean.txt', implode("\n", $cleanList));
echo "Clean key list saved to: /tmp/unused-keys-clean.txt\n";
