package app

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

	"golang.org/x/term"

	"github.com/ClareAI/astra-insight-mcp/internal/config"
)

const defaultOpenRouterBase = "https://openrouter.ai/api/v1"

// RunConfigure implements `astra configure` — save LLM API key and options to ~/.astra/llm.json.
func RunConfigure(args []string) {
	fs := flag.NewFlagSet("configure", flag.ExitOnError)
	apiKeyFlag := fs.String("api-key", "", "LLM API key (OpenRouter, OpenAI, etc.); if empty, prompts interactively")
	baseURLFlag := fs.String("base-url", "", "API base URL (default when empty: "+defaultOpenRouterBase+" for interactive setup)")
	modelFlag := fs.String("model", "", "Model id (default: anthropic/claude-sonnet-4)")
	showPath := fs.Bool("show-path", false, "Print config file path and exit")

	fs.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: astra configure [flags]\n\n")
		fmt.Fprintf(os.Stderr, "Save LLM credentials to ~/.astra/llm.json (mode 0600), similar to a first-run API key setup.\n")
		fmt.Fprintf(os.Stderr, "Environment variables still override the file when you run the REPL.\n\n")
		fmt.Fprintf(os.Stderr, "Examples:\n")
		fmt.Fprintf(os.Stderr, "  astra configure                    # interactive (hidden API key)\n")
		fmt.Fprintf(os.Stderr, "  astra configure --api-key sk-or-...\n")
		fmt.Fprintf(os.Stderr, "  astra configure --show-path        # show where config is stored\n\n")
		fmt.Fprintf(os.Stderr, "Flags:\n")
		fs.PrintDefaults()
	}

	if err := fs.Parse(args); err != nil {
		os.Exit(1)
	}

	path, err := config.LLMFilePath()
	if err != nil {
		fmt.Fprintf(os.Stderr, "[configure] error: %v\n", err)
		os.Exit(1)
	}

	if *showPath {
		fmt.Println(path)
		return
	}

	existing, _ := config.LoadLLMFile()

	apiKey := strings.TrimSpace(*apiKeyFlag)
	if apiKey == "" {
		if !term.IsTerminal(int(os.Stdin.Fd())) || !term.IsTerminal(int(os.Stderr.Fd())) {
			fmt.Fprintf(os.Stderr, "[configure] stdin is not a TTY. Pass --api-key or run in a terminal.\n")
			os.Exit(1)
		}
		fmt.Fprintf(os.Stderr, "%sEnter LLM API key (OpenRouter recommended; input hidden):%s ", replYellow, replReset)
		pw, err := term.ReadPassword(int(os.Stdin.Fd()))
		fmt.Fprintln(os.Stderr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s[configure] failed to read key: %v%s\n", replYellow, err, replReset)
			os.Exit(1)
		}
		apiKey = strings.TrimSpace(string(pw))
	}

	if apiKey == "" {
		fmt.Fprintf(os.Stderr, "%s[configure] API key cannot be empty%s\n", replYellow, replReset)
		os.Exit(1)
	}

	baseURL := strings.TrimSpace(*baseURLFlag)
	if baseURL == "" {
		def := existing.BaseURL
		if def == "" {
			def = defaultOpenRouterBase
		}
		baseURL = readLineDefault(fmt.Sprintf("API base URL [%s]: ", def), def)
	}

	model := strings.TrimSpace(*modelFlag)
	if model == "" {
		def := existing.Model
		if def == "" {
			def = "anthropic/claude-sonnet-4"
		}
		model = readLineDefault(fmt.Sprintf("Model [%s]: ", def), def)
	}

	cfg := config.LLMEnv{
		APIKey:  apiKey,
		BaseURL: baseURL,
		Model:   model,
		// fast model: leave empty in file; derived at runtime from model
	}

	if err := config.SaveLLMFile(cfg); err != nil {
		fmt.Fprintf(os.Stderr, "[configure] error saving: %v\n", err)
		os.Exit(1)
	}

	fmt.Fprintf(os.Stderr, "[configure] Saved LLM settings to %s\n", path)
	fmt.Fprintf(os.Stderr, "  Run `astra` to start the REPL. Set LLM_* env vars to override for a single session.\n")
}

func readLineDefault(prompt, defaultVal string) string {
	fmt.Fprintf(os.Stderr, "%s%s%s", replDim, prompt, replReset)
	line, err := bufio.NewReader(os.Stdin).ReadString('\n')
	if err != nil {
		return defaultVal
	}
	s := strings.TrimSpace(strings.TrimRight(line, "\r\n"))
	if s == "" {
		return defaultVal
	}
	return s
}
