package main

import (
	"flag"
	"log"
	"strings"

	"gitea.boner.be/bdnugget/goonscape/config"
	"gitea.boner.be/bdnugget/goonscape/game"
	"gitea.boner.be/bdnugget/goonscape/logging"
	"gitea.boner.be/bdnugget/goonscape/network"
	rl "github.com/gen2brain/raylib-go/raylib"
)

func main() {
	logging.Info.Println("Starting GoonScape client")

	// Raylib log level warn
	rl.SetTraceLogLevel(rl.LogWarning)
	// Parse command line flags
	local := flag.Bool("local", false, "Connect to local server")
	addr := flag.String("addr", "", "Server address (host or host:port)")
	noMusic := flag.Bool("no-music", false, "Disable music playback")
	flag.Parse()

	// Set config before any game initialization
	config.Current.PlayMusic = !*noMusic

	// Set server address based on flags
	if *local {
		if *addr != "" {
			log.Fatal("Cannot use -local and -addr together")
		}
		network.SetServerAddr("localhost:6969")
	} else if *addr != "" {
		// If port is not specified, append default port
		if !strings.Contains(*addr, ":") {
			*addr += ":6969"
		}
		network.SetServerAddr(*addr)
	}

	logging.Info.Println("Initializing window")
	rl.InitWindow(1024, 768, "GoonScape")
	defer func() {
		logging.Info.Println("Closing window")
		rl.CloseWindow()
	}()

	// Initialize audio device first
	if !rl.IsAudioDeviceReady() {
		rl.InitAudioDevice()
		if !rl.IsAudioDeviceReady() {
			log.Fatal("Failed to initialize audio device")
		}
	}
	defer rl.CloseAudioDevice()

	game := game.New()
	logging.Info.Println("Loading game assets")
	if err := game.LoadAssets(); err != nil {
		log.Fatalf("Failed to load assets: %v", err)
	}
	defer func() {
		logging.Info.Println("Cleaning up game resources")
		game.Cleanup()
	}()

	if config.Current.PlayMusic {
		logging.Info.Println("Starting music playback")
		rl.PlayMusicStream(game.Music)
		rl.SetMusicVolume(game.Music, 0.5)
	}

	rl.SetTargetFPS(60)
	logging.Info.Println("Starting game loop")
	game.Run()
	logging.Info.Println("Game exited cleanly")
}
