package main

import (
	"context"
	"errors"
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	var config demoConfig
	flag.StringVar(&config.ListenAddr, "listen", envOr("LUCKY_ROOM_DEMO_LISTEN", "127.0.0.1:8789"), "local demo listen address")
	flag.StringVar(&config.GatewayBaseURL, "gateway", envOr("LUCKY_ROOM_DEMO_GATEWAY", "http://127.0.0.1:13000"), "gateway-service base URL")
	flag.StringVar(&config.AdminBaseURL, "admin", envOr("LUCKY_ROOM_DEMO_ADMIN", "http://127.0.0.1:13100"), "admin base URL")
	flag.StringVar(&config.AdminUsername, "admin-user", envOr("LUCKY_ROOM_DEMO_ADMIN_USER", "admin"), "local admin username")
	flag.StringVar(&config.AdminPassword, "admin-password", os.Getenv("LUCKY_ROOM_DEMO_ADMIN_PASSWORD"), "local admin password; prefer the environment variable")
	flag.StringVar(&config.WalletAddr, "wallet", envOr("LUCKY_ROOM_DEMO_WALLET", "127.0.0.1:13004"), "wallet-service gRPC address")
	flag.StringVar(&config.LuckyGiftAddr, "lucky", envOr("LUCKY_ROOM_DEMO_LUCKY", "127.0.0.1:13013"), "lucky-gift-service gRPC address")
	flag.StringVar(&config.AppCode, "app", envOr("LUCKY_ROOM_DEMO_APP", "lalu"), "App scope")
	flag.Int64Var(&config.InitialCoins, "initial-coins", 1_000_000, "exact sender COIN balance after fixture setup")
	flag.Parse()

	if config.AdminPassword == "" {
		log.Fatal("LUCKY_ROOM_DEMO_ADMIN_PASSWORD is required; the local page never stores administrator credentials")
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	demo, err := newDemoServer(config)
	if err != nil {
		log.Fatal(err)
	}
	defer demo.Close()

	server := &http.Server{
		Addr:              config.ListenAddr,
		Handler:           demo.Routes(),
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       60 * time.Second,
	}
	go func() {
		<-ctx.Done()
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		_ = server.Shutdown(shutdownCtx)
	}()

	log.Printf("lucky gift voice-room demo: http://%s", config.ListenAddr)
	log.Printf("real API upstream: %s", config.GatewayBaseURL)
	if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatal(err)
	}
}

func envOr(name, fallback string) string {
	if value := os.Getenv(name); value != "" {
		return value
	}
	return fallback
}
