package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"

	"git.threefold.info/herocode/heroagent/pkg/servers/heroagent"
)

func main() {
	// Parse command-line flags
	redisPortFlag := flag.Int("redisport", 6378, "Port to run the Redis server on")
	webdavPortFlag := flag.Int("webdavport", 9001, "Port to run the WebDAV server on")
	uiPortFlag := flag.Int("uiport", 9002, "Port to run the UI server on")

	// Flags to enable/disable specific servers
	enableRedisFlag := flag.Bool("redis", true, "Enable Redis server")
	enableWebDAVFlag := flag.Bool("webdav", true, "Enable WebDAV server")
	enableUIFlag := flag.Bool("ui", true, "Enable UI server")
	enableJobsFlag := flag.Bool("jobs", true, "Enable Job Manager")

	flag.Parse()

	// Initialize ServerFactory with default configuration
	config := heroagent.DefaultConfig()

	// Override with command-line flags if provided
	config.Redis.TCPPort = *redisPortFlag
	config.WebDAV.Config.TCPPort = *webdavPortFlag
	config.UI.Port = strconv.Itoa(*uiPortFlag)

	// Set server enable flags
	config.EnableRedis = *enableRedisFlag
	config.EnableWebDAV = *enableWebDAVFlag
	config.EnableUI = *enableUIFlag
	config.EnableJobs = *enableJobsFlag

	// Override with environment variables if provided
	if redisPortStr := os.Getenv("REDIS_PORT"); redisPortStr != "" {
		if port, err := strconv.Atoi(redisPortStr); err == nil {
			config.Redis.TCPPort = port
		}
	}
	if webdavPortStr := os.Getenv("WEBDAV_PORT"); webdavPortStr != "" {
		if port, err := strconv.Atoi(webdavPortStr); err == nil {
			config.WebDAV.Config.TCPPort = port
		}
	}
	if uiPort := os.Getenv("UI_PORT"); uiPort != "" {
		config.UI.Port = uiPort
	}

	// Create ServerFactory instance
	factory := heroagent.New(config)

	// Start all servers
	fmt.Println("Starting HeroAgent servers...")
	if err := factory.Start(); err != nil {
		log.Fatalf("Failed to start servers: %v", err)
	}

	fmt.Printf("All servers started successfully:\n")
	if config.EnableRedis {
		fmt.Printf("- Redis server running on port %d\n", config.Redis.TCPPort)
	}
	if config.EnableWebDAV {
		fmt.Printf("- WebDAV server running on port %d\n", config.WebDAV.Config.TCPPort)
	}
	if config.EnableUI {
		fmt.Printf("- UI server running on port %s\n", config.UI.Port)
	}
	if config.EnableJobs {
		fmt.Printf("- Job Manager running\n")
	}

	// Keep the main goroutine running
	select {}
}
