<?php
/**
 * Rebuild changelog-data.html from docs/CHANGELOG.md
 * One-time script — delete after use.
 */

$md = file_get_contents(__DIR__ . '/../docs/CHANGELOG.md');
$lines = explode("\n", $md);

$entries = [];
$currentVersion = null;
$currentDate = null;
$currentLines = [];

foreach ($lines as $line) {
    // Match: ## ver. 0.341 (2026-03-16) - Description here
    if (preg_match('/^## ver\. ([\d.]+) \((\d{4}-\d{2}-\d{2})\) - (.+)$/', $line, $m)) {
        // Save previous entry
        if ($currentVersion !== null) {
            $entries[] = [
                'version' => $currentVersion,
                'date' => $currentDate,
                'lines' => $currentLines,
            ];
        }
        $currentVersion = $m[1];
        $currentDate = $m[2];
        $currentLines = [];
    } elseif ($currentVersion !== null && trim($line) !== '' && trim($line) !== '---') {
        // Clean markdown formatting for HTML
        $clean = $line;
        $clean = preg_replace('/^\- \*\*([A-Z]+)\*\*: /', '$1 - ', $clean);
        $clean = preg_replace('/`([^`]+)`/', '$1', $clean);
        $clean = str_replace(['**', '__'], '', $clean);
        $clean = trim($clean);
        if ($clean) {
            $currentLines[] = $clean;
        }
    }
}
// Last entry
if ($currentVersion !== null) {
    $entries[] = [
        'version' => $currentVersion,
        'date' => $currentDate,
        'lines' => $currentLines,
    ];
}

// Build HTML
$html = '';
foreach ($entries as $entry) {
    $dateParts = explode('-', $entry['date']);
    $dateFormatted = $dateParts[2] . '.' . $dateParts[1] . '.' . $dateParts[0];

    $desc = implode("\n", $entry['lines']);
    $desc = htmlspecialchars($desc, ENT_QUOTES, 'UTF-8');

    $html .= '<b>ver. ' . $entry['version'] . ' - ' . $dateFormatted . '</b><br />' . "\n";
    $html .= $desc . "\n";
    $html .= '<hr>' . "\n";
}

$outPath = __DIR__ . '/../updates/changelog-data.html';
file_put_contents($outPath, $html);

$size = filesize($outPath);
echo "Generated " . count($entries) . " entries\n";
echo "File size: " . number_format($size) . " bytes\n";
echo "Output: $outPath\n";
