namespace Msys2Manager.Core.Configuration;

public class Msys2LockFile
{
    public Dictionary<string, string> Packages { get; set; } = new();

    public static Msys2LockFile Parse(string content)
    {
        var lockFile = new Msys2LockFile();

        foreach (var line in content.Split('\n'))
        {
            var trimmed = line.Trim();
            if (string.IsNullOrWhiteSpace(trimmed) || trimmed.StartsWith('#'))
                continue;

            var parts = trimmed.Split('=', 2);
            if (parts.Length == 2)
            {
                lockFile.Packages[parts[0].Trim()] = parts[1].Trim();
            }
        }

        return lockFile;
    }

    public string Serialize()
    {
        var lines = new List<string>
        {
            $"# Generated by M2M v{GetType().Assembly.GetName().Version?.ToString(3) ?? "1.0.0"}",
            $"# {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
            ""
        };

        foreach (var (name, version) in Packages.OrderBy(x => x.Key))
        {
            lines.Add($"{name}={version}");
        }

        return string.Join("\n", lines);
    }
}
