// Sipp CLI: minimal command dispatcher.
//
//	sipp                              launch the interactive TUI
//	sipp tui [-r URL] [-k KEY]        launch the interactive TUI
//	sipp auth                         save remote URL + API key to config
//	sipp server [--host H] [--port P] start the web server
//	sipp [-r URL] [-k KEY] <file>     upload a file to a remote sipp server
//	sipp --help
package main

import (
	"fmt"
	"os"
	"strconv"

	"github.com/stevedylandev/andromeda/apps/sipp/server"
	"github.com/stevedylandev/andromeda/apps/sipp/tui"
	"github.com/stevedylandev/andromeda/pkg/config"
)

const usage = `sipp — minimal code sharing CLI

usage:
  sipp                              launch interactive TUI
  sipp tui [-r URL] [-k KEY]        launch interactive TUI
  sipp auth                         save remote URL + API key to ~/.config/sipp/config.toml
  sipp server [--host HOST] [--port PORT]
  sipp [-r URL] [-k KEY] <file>     create a snippet from FILE on the remote server
  sipp --help

env:
  SIPP_REMOTE_URL  default remote URL
  SIPP_API_KEY     API key used for authenticated requests
  SIPP_DB_PATH     local sqlite path for TUI in local mode
`

func main() {
	args := os.Args[1:]
	if len(args) == 0 {
		runTUI(nil)
		return
	}
	switch args[0] {
	case "-h", "--help":
		fmt.Print(usage)
	case "server":
		runServer(args[1:])
	case "tui":
		runTUI(args[1:])
	case "auth":
		runAuth(args[1:])
	default:
		runUpload(args)
	}
}

func runServer(args []string) {
	config.LoadDotEnv(".env")
	host := config.Getenv("HOST", "127.0.0.1")
	port := config.GetenvInt("PORT", 3000)
	for i := 0; i < len(args); i++ {
		switch args[i] {
		case "--host":
			if i+1 < len(args) {
				host = args[i+1]
				i++
			}
		case "--port", "-p":
			if i+1 < len(args) {
				if n, err := strconv.Atoi(args[i+1]); err == nil {
					port = n
				}
				i++
			}
		}
	}
	if err := server.Run(host, port); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func runTUI(args []string) {
	if err := tui.Run(tui.ParseArgs(args)); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
