using System.IO;
using System.Security.Cryptography;

namespace ClaudeDo.Releases;

public static class ChecksumVerifier
{
    public static string ComputeSha256(string filePath)
    {
        using var stream = File.OpenRead(filePath);
        using var sha = SHA256.Create();
        var hash = sha.ComputeHash(stream);
        return Convert.ToHexString(hash).ToLowerInvariant();
    }

    public static bool Verify(string filePath, string expectedSha256)
    {
        var actual = ComputeSha256(filePath);
        return string.Equals(actual, expectedSha256.Trim(), StringComparison.OrdinalIgnoreCase);
    }

    public static IReadOnlyDictionary<string, string> ParseChecksumsFile(string content)
    {
        var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        foreach (var rawLine in content.Split('\n'))
        {
            var line = rawLine.Trim();
            if (line.Length == 0) continue;
            var parts = line.Split(new[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length != 2) continue;
            var hashPart = parts[0].Trim();
            if (hashPart.Length != 64) continue;
            map[parts[1].Trim()] = hashPart;
        }
        return map;
    }
}
