namespace NATS.Server.Tests.Parity;

public sealed record ParityRow(string Section, string SubSection, string Feature, string DotNetStatus);

public sealed class ParityReport
{
    public ParityReport(IReadOnlyList<ParityRow> rows)
    {
        Rows = rows;
    }

    public IReadOnlyList<ParityRow> Rows { get; }

    public IReadOnlyList<ParityRow> UnresolvedRows =>
        Rows.Where(r => r.DotNetStatus is "N" or "Baseline" or "Stub").ToArray();
}

public static class ParityRowInspector
{
    public static ParityReport Load(string relativePath)
    {
        var repositoryRoot = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", ".."));
        var differencesPath = Path.Combine(repositoryRoot, relativePath);
        File.Exists(differencesPath).ShouldBeTrue();

        var section = string.Empty;
        var subsection = string.Empty;
        var rows = new List<ParityRow>();
        foreach (var rawLine in File.ReadLines(differencesPath))
        {
            var line = rawLine.Trim();
            if (line.StartsWith("## ", StringComparison.Ordinal))
            {
                section = line[3..].Trim();
                continue;
            }

            if (line.StartsWith("### ", StringComparison.Ordinal))
            {
                subsection = line[4..].Trim();
                continue;
            }

            if (!line.StartsWith("|", StringComparison.Ordinal))
                continue;

            if (line.Contains("---", StringComparison.Ordinal))
                continue;

            var cells = line.Trim('|').Split('|').Select(c => c.Trim()).ToArray();
            if (cells.Length < 3)
                continue;

            // Ignore table header rows; row format is expected to contain Go and .NET status columns.
            if (cells[0] is "Feature" or "Aspect" or "Operation" or "Signal" or "Type" or "Mechanism" or "Flag")
                continue;

            rows.Add(new ParityRow(
                section,
                subsection,
                cells[0],
                cells[2]));
        }

        return new ParityReport(rows);
    }
}
