package main

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

	"marte2debugger/controller"

	"marte2/common/wshub"
)

var buildVersion = "dev"

//go:embed static
var staticFiles embed.FS

func main() {
	addr := flag.String("addr", ":7777", "HTTP listen address")
	sourcesFile := flag.String("sources-file", "", "JSON file for persistent source list")
	flag.BoolVar(&controller.DangerousCommandsEnabled, "enable-dangerous-commands", false,
		"Allow FORCE/PAUSE/RESUME/STEP/BREAK/MSG commands from the browser (CR-4 safety gate)")
	flag.Parse()

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

	ctrl := controller.NewMarteController(hub)

	go hub.Run()

	// Load persisted sources
	if *sourcesFile != "" {
		if err := sm.Load(*sourcesFile); err != nil && !errors.Is(err, os.ErrNotExist) {
			log.Printf("sources-file load: %v", err)
		}
	}

	// Register the debug source (always present; state managed by MarteController)
	hub.AddSource("debug", "MARTe2 Debug", "")

	// Forward browser debug commands to MarteController
	go func() {
		for msg := range hub.DebugCh {
			ctrl.HandleBrowserCommand(msg)
		}
	}()

	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("MARTe2 Integrated Client listening on %s (build=%s)", *addr, buildVersion)
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatalf("http: %v", err)
	}
}
