<?php

/**
 * Generate a CSV file for manual review of unused translation keys
 */

$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 "Found " . count($keys) . " unused keys\n";
echo "Generating CSV file...\n";

// Create CSV
$csv = fopen('unused-keys-review.csv', 'w');

// Write header
fputcsv($csv, ['Key', 'Value', 'Category', 'Action', 'Notes']);

// Write data rows
foreach ($keys as $key => $value) {
    // Determine category from key prefix
    $parts = explode('.', $key);
    $category = count($parts) > 1 ? $parts[0] : 'other';

    fputcsv($csv, [$key, $value, $category, '', '']);
}

fclose($csv);

echo "CSV file created: unused-keys-review.csv\n";
echo "Total keys: " . count($keys) . "\n\n";

// Show category breakdown
$categories = [];
foreach ($keys as $key => $value) {
    $parts = explode('.', $key);
    $category = count($parts) > 1 ? $parts[0] : 'other';

    if (!isset($categories[$category])) {
        $categories[$category] = 0;
    }
    $categories[$category]++;
}

arsort($categories);

echo "Breakdown by category:\n";
echo str_repeat('-', 50) . "\n";
foreach ($categories as $cat => $count) {
    printf("  %-30s %4d keys\n", $cat, $count);
}

echo "\nYou can now open 'unused-keys-review.csv' in a spreadsheet application\n";
echo "to manually review and mark which keys to keep or delete.\n";
