<?php

declare(strict_types=1);

namespace Lab;

final class Changelog
{
    public static function path(): string
    {
        return dirname(__DIR__) . '/CHANGELOG.md';
    }

    /** @return list<string> */
    public static function notesFor(string $version, ?string $file = null): array
    {
        $all = self::all($file);

        return $all[$version] ?? [];
    }

    /** @return array<string, list<string>> */
    public static function all(?string $file = null): array
    {
        $file ??= self::path();
        $raw = @file_get_contents($file);
        if (! is_string($raw) || $raw === '') {
            return [];
        }

        $out = [];
        $ver = '';
        foreach (preg_split('/\R/u', $raw) ?: [] as $line) {
            if (preg_match('/^##\s+(\d+\.\d+\.\d+)/', $line, $m) === 1) {
                $ver = $m[1];
                $out[$ver] = [];
                continue;
            }
            if ($ver !== '' && preg_match('/^-\s+(.+)/', $line, $m) === 1) {
                $out[$ver][] = trim($m[1]);
            }
        }

        return $out;
    }
}
