// Command webrtc-poc runs a minimal Dragon Fork WebRTC egress server for
// manual end-to-end testing. It listens for RTP on 127.0.0.1:10000 as
// stream "test" and serves WHEP at :8787.
//
// This is NOT part of the datarhei Core binary. It will be removed or
// demoted to an internal test helper once milestone M2 lands.
package main

import (
	"flag"
	"log"
	"net/http"

	"github.com/datarhei/core/v16/core/webrtc"
)

func main() {
	var (
		streamID = flag.String("stream", "test", "stream id to serve")
		rtpHost  = flag.String("rtp-host", "127.0.0.1", "bind address for RTP UDP socket (use 0.0.0.0 for LAN publishers)")
		rtpPort  = flag.Int("rtp-port", 10000, "UDP port to receive RTP on")
		listen   = flag.String("listen", ":8787", "WHEP HTTP listen address")
		publicIP = flag.String("public-ip", "", "server public IP for NAT1To1 (optional)")
	)
	flag.Parse()

	cfg := webrtc.DefaultConfig()
	cfg.WHEPListen = *listen
	cfg.PublicIP = *publicIP

	src, err := webrtc.NewSourceOn(*streamID, *rtpHost, *rtpPort)
	if err != nil {
		log.Fatalf("NewSource: %v", err)
	}
	src.Start()
	defer src.Close()
	log.Printf("listening for RTP on %s", src.LocalAddr())

	reg := webrtc.NewRegistry()
	if err := reg.Register(*streamID, src); err != nil {
		log.Fatalf("Register: %v", err)
	}

	factory, err := webrtc.NewPeerFactory(cfg)
	if err != nil {
		log.Fatalf("NewPeerFactory: %v", err)
	}

	handler := webrtc.NewWHEPHandler(reg, factory, cfg)

	mux := http.NewServeMux()
	mux.Handle("/whep/", handler)

	log.Printf("WHEP listening on %s — POST /whep/%s to subscribe", *listen, *streamID)
	log.Fatal(http.ListenAndServe(*listen, mux))
}
