using System.CommandLine;
using NatsNet.PortTracker.Data;
using NatsNet.PortTracker.Reporting;

namespace NatsNet.PortTracker.Commands;

public static class ReportCommands
{
    public static Command Create(Option<string> dbOption, Option<string> schemaOption)
    {
        var reportCommand = new Command("report", "Generate reports");

        // summary
        var summaryCmd = new Command("summary", "Show status summary");
        summaryCmd.SetAction(parseResult =>
        {
            var dbPath = parseResult.GetValue(dbOption)!;
            using var db = new Database(dbPath);
            ReportGenerator.PrintSummary(db);
        });

        // export
        var exportFormat = new Option<string>("--format") { Description = "Export format (md)", DefaultValueFactory = _ => "md" };
        var exportOutput = new Option<string?>("--output") { Description = "Output file path (stdout if not specified)" };
        var exportCmd = new Command("export", "Export status report");
        exportCmd.Add(exportFormat);
        exportCmd.Add(exportOutput);
        exportCmd.SetAction(parseResult =>
        {
            var dbPath = parseResult.GetValue(dbOption)!;
            var format = parseResult.GetValue(exportFormat)!;
            var output = parseResult.GetValue(exportOutput);
            using var db = new Database(dbPath);

            if (format != "md")
            {
                Console.WriteLine($"Unsupported format: {format}. Supported: md");
                return;
            }

            var markdown = ReportGenerator.ExportMarkdown(db);
            if (output is not null)
            {
                File.WriteAllText(output, markdown);
                Console.WriteLine($"Report exported to {output}");
            }
            else
            {
                Console.Write(markdown);
            }
        });

        reportCommand.Add(summaryCmd);
        reportCommand.Add(exportCmd);

        return reportCommand;
    }
}
