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

namespace AsyncApiRenderer;

public static class Program
{
    public static string Prefix { get; private set; } = "";

    public static async Task Main(string[] args)
    {
        if (args.Length == 0 || !File.Exists(args[0]))
        {
            Console.Error.WriteLine("Expect first argument to be json spec");
            Environment.ExitCode = 1;
            return;
        }
        if (args.Length == 1 || args[1] == "asyncapi")
        {
            if (args.Length > 2)
                Prefix = args[2];
            using var stream = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read);
            var data = await JsonSerializer.DeserializeAsync<Data.DataFile>(
                stream,
                new JsonSerializerOptions
                {
                    AllowTrailingCommas = true,
                    PropertyNameCaseInsensitive = true,
                    ReadCommentHandling = JsonCommentHandling.Skip,
                }
            );
            if (data is null)
            {
                Console.Error.WriteLine("Expected input is not valid json format");
                Environment.ExitCode = 2;
                return;
            }
            data.Deref();
            data.Collapse();
            var renderer = new Renderer.PandocMarkdownRenderer();
            renderer.Render(data, Console.Out);
            return;
        }
        if (args[1] == "json-schema")
        {
            using var stream = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read);
            var data = await JsonSerializer.DeserializeAsync<Data.JsonSchemaNode>(
                stream,
                new JsonSerializerOptions
                {
                    AllowTrailingCommas = true,
                    PropertyNameCaseInsensitive = true,
                    ReadCommentHandling = JsonCommentHandling.Skip,
                }
            );
            if (data is null)
            {
                Console.Error.WriteLine("Expected input is not valid json format");
                Environment.ExitCode = 2;
                return;
            }
            data.Collapse();
            var renderer = new Renderer.PandocMarkdownRenderer();
            renderer.Render(data, Console.Out);
            return;
        }
    }

    public static void DebugWriteJson<T>(T value)
    {
        using var m = new MemoryStream();
        JsonSerializer.Serialize(m, value, new JsonSerializerOptions
        {
            WriteIndented = true,
        });
        Console.Error.Write(System.Text.Encoding.UTF8.GetString(m.ToArray()));
    }
}