package main

import (
	"embed"
	"errors"
	"flag"
	"fmt"
	"io/fs"
	"log"
	"net/http"
	"os"

	"marte2/common/wshub"
)

var buildVersion = "dev"

//go:embed static
var staticFiles embed.FS

// multiFlag allows a flag to be repeated: --source a --source b
type multiFlag []string

func (f *multiFlag) String() string        { return fmt.Sprintf("%v", []string(*f)) }
func (f *multiFlag) Set(v string) error    { *f = append(*f, v); return nil }

func main() {
	var sourceArgs multiFlag
	flag.Var(&sourceArgs, "source", `Data source in the form [label@]host:port[/multicastGroup:dataPort] (repeatable)`)
	sourcesFile := flag.String("sources-file", "", "JSON file for persistent source list (load on start, save target)")
	listenAddr := flag.String("addr", ":8080", "HTTP listen address")
	flag.Parse()

	hub := wshub.NewHub()
	sm := wshub.NewSourceManager(hub, *sourcesFile)
	hub.SetSourceManager(sm)

	go hub.Run()

	// Load sources from file first (if specified), then add any CLI --source flags.
	if *sourcesFile != "" {
		if err := sm.Load(*sourcesFile); err != nil && !errors.Is(err, os.ErrNotExist) {
			log.Printf("sources-file load: %v", err)
		}
	}
	for _, arg := range sourceArgs {
		label, addr, mcastGroup, dataPort := wshub.ParseSourceArgFull(arg)
		sm.Add(label, addr, mcastGroup, dataPort)
	}

	sub, err := fs.Sub(staticFiles, "static")
	if err != nil {
		log.Fatalf("static sub-fs: %v", err)
	}
	http.Handle("/", http.FileServer(http.FS(sub)))
	http.HandleFunc("/ws", hub.HandleWebSocket)
	http.HandleFunc("/api/zoom", hub.HandleZoom)
	http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, buildVersion)
	})

	log.Printf("UDPStreamer WebUI listening on %s (build=%s)", *listenAddr, buildVersion)
	if err := http.ListenAndServe(*listenAddr, nil); err != nil {
		log.Fatalf("http: %v", err)
	}
}
