package main

import (
	"flag"
	"log"
	"path/filepath"
	"strings"

	"omnisocketgo/cmd/internal/latencylog"
)

type stringListFlag []string

func (f *stringListFlag) String() string {
	return ""
}

func (f *stringListFlag) Set(value string) error {
	*f = append(*f, value)
	return nil
}

func main() {
	var inputPaths stringListFlag
	outputPath := flag.String("output", "latency-summary.jsonl", "output JSONL file for summarized latency metrics")
	flag.Var(&inputPaths, "input", "raw latency JSONL file path; can be provided multiple times")
	flag.Parse()

	if len(inputPaths) == 0 {
		log.Fatal("at least one -input raw latency log file is required")
	}

	events, err := latencylog.LoadEventsFromFiles(inputPaths)
	if err != nil {
		log.Fatalf("load raw latency logs: %v", err)
	}

	summaries := latencylog.SummarizeEvents(events)
	if err := latencylog.WriteSummariesJSONL(*outputPath, summaries); err != nil {
		log.Fatalf("write latency summary: %v", err)
	}

	chartPath := replaceFileExt(*outputPath, ".html")
	if err := latencylog.WriteSummariesHTMLChart(chartPath, summaries); err != nil {
		log.Fatalf("write latency chart: %v", err)
	}

	log.Printf("wrote %d summarized message records to %s", len(summaries), *outputPath)
	log.Printf("wrote simple latency chart to %s", chartPath)
}

func replaceFileExt(path, ext string) string {
	currentExt := filepath.Ext(path)
	if currentExt == "" {
		return path + ext
	}

	return strings.TrimSuffix(path, currentExt) + ext
}
