using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace StellaOps.Feedser.Source.Distro.Suse.Internal;

internal static class SuseChangesParser
{
    public static IReadOnlyList<SuseChangeRecord> Parse(string csv)
    {
        if (string.IsNullOrWhiteSpace(csv))
        {
            return Array.Empty<SuseChangeRecord>();
        }

        var records = new List<SuseChangeRecord>();
        using var reader = new StringReader(csv);
        string? line;
        while ((line = reader.ReadLine()) is not null)
        {
            if (string.IsNullOrWhiteSpace(line))
            {
                continue;
            }

            var parts = SplitCsvLine(line);
            if (parts.Length < 2)
            {
                continue;
            }

            var fileName = parts[0].Trim();
            if (string.IsNullOrWhiteSpace(fileName))
            {
                continue;
            }

            if (!DateTimeOffset.TryParse(parts[1], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var modifiedAt))
            {
                continue;
            }

            records.Add(new SuseChangeRecord(fileName, modifiedAt.ToUniversalTime()));
        }

        return records;
    }

    private static string[] SplitCsvLine(string line)
    {
        var values = new List<string>(2);
        var current = string.Empty;
        var insideQuotes = false;

        foreach (var ch in line)
        {
            if (ch == '"')
            {
                insideQuotes = !insideQuotes;
                continue;
            }

            if (ch == ',' && !insideQuotes)
            {
                values.Add(current);
                current = string.Empty;
                continue;
            }

            current += ch;
        }

        if (!string.IsNullOrEmpty(current))
        {
            values.Add(current);
        }

        return values.ToArray();
    }
}
