using System.Text.Json;
using System.Text.Json.Serialization;

namespace ZB.MOM.WW.ScadaBridge.CLI;

public static class OutputFormatter
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        WriteIndented = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    /// <summary>Serializes <paramref name="data"/> to indented JSON and writes it to standard output.</summary>
    /// <param name="data">The object to serialize; <c>null</c> is serialized as JSON <c>null</c>.</param>
    public static void WriteJson(object? data)
    {
        Console.WriteLine(JsonSerializer.Serialize(data, JsonOptions));
    }

    /// <summary>Writes a JSON error envelope with the given message and code to standard error.</summary>
    /// <param name="message">Human-readable error description.</param>
    /// <param name="code">Machine-readable error code.</param>
    public static void WriteError(string message, string code)
    {
        Console.Error.WriteLine(JsonSerializer.Serialize(new { error = message, code }, JsonOptions));
    }

    /// <summary>Writes a plain-text padded table to standard output with the given column headers and data rows.</summary>
    /// <param name="rows">Data rows; each inner array corresponds to a column in the same order as <paramref name="headers"/>.</param>
    /// <param name="headers">Column header labels.</param>
    public static void WriteTable(IEnumerable<string[]> rows, string[] headers)
    {
        var allRows = new List<string[]> { headers };
        allRows.AddRange(rows);
        var widths = new int[headers.Length];
        foreach (var row in allRows)
            for (int i = 0; i < Math.Min(row.Length, widths.Length); i++)
                widths[i] = Math.Max(widths[i], (row[i] ?? "").Length);

        foreach (var row in allRows)
        {
            for (int i = 0; i < headers.Length; i++)
                Console.Write((i < row.Length ? row[i] ?? "" : "").PadRight(widths[i] + 2));
            Console.WriteLine();
        }
    }
}
