package main

import (
	"flag"
	"fmt"
	"grokway/internal/config"
	"grokway/internal/tui"
	"os"

	tea "github.com/charmbracelet/bubbletea"
)

func main() {
	// Subcommand handling
	if len(os.Args) > 1 && os.Args[1] == "configure" {
		configureCmd := flag.NewFlagSet("configure", flag.ExitOnError)
		tokenFlag := configureCmd.String("token", "", "Authentication token")
		serverFlag := configureCmd.String("server", "", "Grokway server address (e.g., localhost:2222)")
		configureCmd.Parse(os.Args[2:])

		if *tokenFlag == "" {
			fmt.Println("Error: --token is required")
			os.Exit(1)
		}

		if err := config.Save(*tokenFlag, *serverFlag); err != nil {
			fmt.Printf("Error saving config: %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Configuration saved successfully!")
		return
	}

	// Normal run
	localPort := flag.String("local", "8080", "Local port to expose")
	serverAddrFlag := flag.String("server", "", "Grokway server address")
	tokenFlag := flag.String("token", "", "Authentication token (overrides config)")
	hostHeaderFlag := flag.String("host-header", "", "Custom Host header to send to local service")
	localHttpsFlag := flag.Bool("local-https", false, "Use HTTPS to connect to local service (implied if port is 443)")
	flag.Parse()

	// Load config
	cfg, err := config.Load()
	authToken := *tokenFlag
	serverAddr := *serverAddrFlag

	if err == nil {
		if authToken == "" {
			authToken = cfg.Token
		}
		if serverAddr == "" {
			serverAddr = cfg.ServerURL
		}
	}

	// Default server address if not specified anywhere
	if serverAddr == "" {
		serverAddr = "localhost:2222"
	}

	m := tui.InitialModel(*localPort, serverAddr, authToken, *hostHeaderFlag, *localHttpsFlag)
	p := tea.NewProgram(m, tea.WithAltScreen())

	if _, err := p.Run(); err != nil {
		fmt.Printf("Alas, there's been an error: %v", err)
		os.Exit(1)
	}
}
