package cmd

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

var configCmd = &cobra.Command{
	Use:   "config",
	Short: "Set your Gitea URL, username, and API token",
	RunE: func(cmd *cobra.Command, args []string) error {
		reader := bufio.NewReader(os.Stdin)

		cfg := &Config{}
		if existing, err := loadConfig(); err == nil {
			*cfg = *existing
		}

		cfg.URL = prompt(reader, fmt.Sprintf("Gitea URL [%s]", cfg.URL), cfg.URL)
		cfg.Username = prompt(reader, fmt.Sprintf("Username [%s]", cfg.Username), cfg.Username)
		cfg.Token = prompt(reader, fmt.Sprintf("API Token [%s]", maskToken(cfg.Token)), cfg.Token)

		fmt.Println("\n--- Homelab / beepc ---")
		cfg.SSHHost = prompt(reader, fmt.Sprintf("SSH host (e.g. beepc) [%s]", cfg.SSHHost), cfg.SSHHost)
		cfg.SSHUser = prompt(reader, fmt.Sprintf("SSH user [%s]", cfg.SSHUser), cfg.SSHUser)
		cfg.ProjectsDir = promptDefault(reader, fmt.Sprintf("Projects dir on host [%s]", cfg.ProjectsDir), cfg.ProjectsDir, "~/projects")
		cfg.HomelabDir = promptDefault(reader, fmt.Sprintf("Homelab repo dir on host [%s]", cfg.HomelabDir), cfg.HomelabDir, "~/homelab")
		proxyDefault := cfg.ProxyHost
		if proxyDefault == "" {
			proxyDefault = cfg.SSHHost
		}
		cfg.ProxyHost = promptDefault(reader, fmt.Sprintf("Proxy host for Caddy (IP/hostname VPS uses to reach beepc) [%s]", proxyDefault), cfg.ProxyHost, proxyDefault)

		fmt.Println("\n--- Caddy ---")
		cfg.CaddyConfDir = promptDefault(reader, fmt.Sprintf("Caddy conf.d dir [%s]", cfg.CaddyConfDir), cfg.CaddyConfDir, "~/caddy/conf.d")
		cfg.CaddyReloadCmd = promptDefault(reader, fmt.Sprintf("Caddy reload command [%s]", cfg.CaddyReloadCmd), cfg.CaddyReloadCmd, "sudo caddy reload")
		cfg.Domain = promptDefault(reader, fmt.Sprintf("Base domain [%s]", cfg.Domain), cfg.Domain, "sketchferret.com")

		fmt.Println("\n--- Port assignment ---")
		portStr := ""
		if cfg.PortStart != 0 {
			portStr = fmt.Sprintf("%d", cfg.PortStart)
		}
		portInput := promptDefault(reader, fmt.Sprintf("Port range start [%s]", portStr), portStr, "8200")
		if p, err := fmt.Sscanf(portInput, "%d", &cfg.PortStart); p == 0 || err != nil {
			cfg.PortStart = 8200
		}

		if err := saveConfig(cfg); err != nil {
			return fmt.Errorf("saving config: %w", err)
		}
		fmt.Println("Config saved to", configPath())
		return nil
	},
}

func prompt(reader *bufio.Reader, label, fallback string) string {
	fmt.Printf("%s: ", label)
	input, _ := reader.ReadString('\n')
	input = strings.TrimSpace(input)
	if input == "" {
		return fallback
	}
	return input
}

// promptDefault returns fallback if input is empty, otherwise defaultVal if fallback is also empty.
func promptDefault(reader *bufio.Reader, label, fallback, defaultVal string) string {
	result := prompt(reader, label, fallback)
	if result == "" {
		return defaultVal
	}
	return result
}

func maskToken(t string) string {
	if len(t) < 4 {
		return "****"
	}
	return t[:4] + "****"
}
