namespace NATS.Server.TestUtilities.Parity;

public sealed record CapabilityRow(string Capability, string Behavior, string Tests, string Docs);

public sealed class NatsCapabilityInventoryReport
{
    public NatsCapabilityInventoryReport(IReadOnlyList<CapabilityRow> rows)
    {
        Rows = rows;
    }

    public IReadOnlyList<CapabilityRow> Rows { get; }

    public IReadOnlyList<CapabilityRow> InvalidRows => Rows
        .Where(r => !IsDone(r.Behavior) && IsClosed(r.Docs))
        .Concat(Rows.Where(r => !IsDone(r.Tests) && IsClosed(r.Docs)))
        .Distinct()
        .ToArray();

    private static bool IsDone(string status) => string.Equals(status, "done", StringComparison.OrdinalIgnoreCase);
    private static bool IsClosed(string status) => string.Equals(status, "closed", StringComparison.OrdinalIgnoreCase);
}

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

        var rows = new List<CapabilityRow>();
        foreach (var rawLine in File.ReadLines(mapPath))
        {
            var line = rawLine.Trim();
            if (!line.StartsWith("|", StringComparison.Ordinal) || line.Contains("---", StringComparison.Ordinal))
                continue;

            var cells = line.Trim('|').Split('|').Select(static c => c.Trim()).ToArray();
            if (cells.Length < 4 || string.Equals(cells[0], "Capability", StringComparison.OrdinalIgnoreCase))
                continue;

            rows.Add(new CapabilityRow(
                cells[0],
                cells[1],
                cells[2],
                cells[3]));
        }

        return new NatsCapabilityInventoryReport(rows);
    }
}
