<?php

/**
 * Display unused translation keys from en.json in a readable format
 */

// Run the find-unused command and capture output
exec('php artisan ai-translator:find-unused --format=table --show-files --no-interaction 2>&1', $output);

$inEnJson = false;
$unusedKeys = [];

foreach ($output as $line) {
    // Check if we're in the en.json section
    if (strpos($line, 'en.json:') !== false) {
        $inEnJson = true;
        continue;
    }

    // Check if we've moved to another file
    if ($inEnJson && preg_match('/^[a-z\-]+\.php:/', $line)) {
        break;
    }

    // Extract the key if we're in en.json section
    if ($inEnJson && preg_match('/│\s+([^\s│]+)\s+│\s+(.+?)\s+│/', $line, $matches)) {
        $key = trim($matches[1]);
        $value = trim($matches[2]);
        if ($key && $value) {
            $unusedKeys[$key] = $value;
        }
    }
}

echo "=== UNUSED TRANSLATION KEYS IN en.json ===\n";
echo "Total: " . count($unusedKeys) . " keys\n";
echo str_repeat('=', 80) . "\n\n";

// Group keys by prefix for easier review
$grouped = [];
foreach ($unusedKeys as $key => $value) {
    $prefix = explode('.', $key)[0];
    if (!isset($grouped[$prefix])) {
        $grouped[$prefix] = [];
    }
    $grouped[$prefix][$key] = $value;
}

// Sort groups alphabetically
ksort($grouped);

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

    foreach ($keys as $key => $value) {
        // Truncate long values for readability
        $displayValue = strlen($value) > 60 ? substr($value, 0, 57) . '...' : $value;
        echo sprintf("  %-40s → %s\n", $key, $displayValue);
    }
}

echo "\n\n" . str_repeat('=', 80) . "\n";
echo "Total unused keys: " . count($unusedKeys) . "\n";
echo "\nNOTE: Some keys may be used dynamically (e.g., __(\$variable))\n";
echo "Please review carefully before deleting.\n";
