package main

import (
	"embed"
	"flag"
	"log"
	"net/http"
	"nymdrop/internal/handler"
	"nymdrop/internal/nolog"
	"nymdrop/internal/nym"
	"nymdrop/internal/pow"
	"nymdrop/internal/relay"
)

//go:embed bin/nym-client-linux-amd64
var nymBin embed.FS

func main() {
	listen         := flag.String("listen", ":8080", "address to listen on")
	tlsCert        := flag.String("tls-cert", "", "TLS certificate path (optional)")
	tlsKey         := flag.String("tls-key", "", "TLS key path (optional)")
	journalistAddr := flag.String("journalist", "", "journalist Nym address (required)")
	staticDir      := flag.String("static", "./static", "path to static files")
	dryRun         := flag.Bool("dry-run", false, "skip Nym, log payloads to stdout (testing only)")
	powBits        := flag.Int("pow-difficulty", 18, "required leading zero bits for the client-side proof of work")
	flag.Parse()

	if *journalistAddr == "" {
		log.Fatal("--journalist is required")
	}

	var nymClient *nym.Client
	if *dryRun {
		nymClient = nym.NewDryRun(*journalistAddr)
	} else {
		nymClient = nym.New(*journalistAddr, nymBin)
	}
	if err := nymClient.Start(); err != nil {
		log.Fatalf("nym client: %v", err)
	}
	defer nymClient.Stop()

	r := relay.New(nymClient)
	powVerifier := pow.NewVerifier(*powBits)

	mux := http.NewServeMux()
	mux.Handle("/submit", handler.NewSubmit(r, powVerifier))
	mux.Handle("/", handler.Static(*staticDir))

	srv := &http.Server{
		Addr:    *listen,
		Handler: nolog.Middleware(mux),
	}

	if *tlsCert != "" && *tlsKey != "" {
		log.Printf("nymdrop listening on %s (TLS)", *listen)
		log.Fatal(srv.ListenAndServeTLS(*tlsCert, *tlsKey))
	} else {
		log.Printf("nymdrop listening on %s (plain HTTP — use TLS in production)", *listen)
		log.Fatal(srv.ListenAndServe())
	}
}
