package main

import (
	"cursor-api-proxy/cmd"
	"cursor-api-proxy/internal/config"
	"cursor-api-proxy/internal/env"
	"cursor-api-proxy/internal/server"
	"fmt"
	"os"
)

const version = "1.0.0"

func main() {
	args, err := cmd.ParseArgs(os.Args[1:])
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}

	if args.Help {
		cmd.PrintHelp(version)
		return
	}

	if args.Login {
		if err := cmd.HandleLogin(args.AccountName, args.Proxies); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	if args.Logout {
		if err := cmd.HandleLogout(args.AccountName); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	if args.AccountsList {
		if err := cmd.HandleAccountsList(); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	if args.ResetHwid {
		if err := cmd.HandleResetHwid(args.DeepClean, args.DryRun); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	e := env.OsEnvToMap()
	if args.Tailscale {
		e["CURSOR_BRIDGE_HOST"] = "0.0.0.0"
	}

	cwd, _ := os.Getwd()
	cfg := config.LoadBridgeConfig(e, cwd)

	servers := server.StartBridgeServer(server.ServerOptions{
		Version: version,
		Config:  cfg,
	})
	server.SetupGracefulShutdown(servers, 10000)

	select {}
}
