package app

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

	"golang.org/x/term"

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

func promptLLMProviderUntilValid() config.LLMProviderID {
	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Fprintf(os.Stderr, "\n%sStep 1/2 — Choose LLM provider:%s\n", replYellow, replReset)
		fmt.Fprintf(os.Stderr, "  %s1%s OpenRouter   %shttps://openrouter.ai%s\n", replGreen, replReset, replDim, replReset)
		fmt.Fprintf(os.Stderr, "  %s2%s Google Gemini %s(AI Studio API key)%s\n", replGreen, replReset, replDim, replReset)
		fmt.Fprintf(os.Stderr, "%sEnter 1 or 2:%s ", replYellow, replReset)
		line, err := reader.ReadString('\n')
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s✗ %v%s\n", replYellow, err, replReset)
			os.Exit(1)
		}
		line = strings.TrimSpace(strings.TrimRight(line, "\r\n"))
		if p, ok := config.ParseLLMProvider(line); ok {
			return p
		}
		fmt.Fprintf(os.Stderr, "%sInvalid choice — type 1 or 2 (or openrouter / gemini).%s\n", replYellow, replReset)
	}
}

func readHiddenAPIKey(prompt string) (string, error) {
	fmt.Fprintf(os.Stderr, "%s%s%s ", replYellow, prompt, replReset)
	pw, err := term.ReadPassword(int(os.Stdin.Fd()))
	fmt.Fprintln(os.Stderr)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(pw)), nil
}

// promptAstraPlatformKey interactively asks the user for their Astra platform
// API key (Step 2/2). Returns the key string, or "" if skipped / non-TTY.
// Caller is responsible for persisting and injecting into the environment.
func promptAstraPlatformKey() string {
	if !term.IsTerminal(int(os.Stdin.Fd())) || !term.IsTerminal(int(os.Stderr.Fd())) {
		return ""
	}

	fmt.Fprintf(os.Stderr, "\n%sStep 2/2 — Astra platform API key%s %s(for agent management tools)%s\n", replYellow, replReset, replDim, replReset)
	fmt.Fprintf(os.Stderr, "%s  Get your key at: %shttps://app.wati.io → Settings → API Keys%s\n", replDim, replReset+replDim, replReset)
	fmt.Fprintf(os.Stderr, "%s  Or press Enter to skip (you can set ASTRA_API_KEY later)%s\n", replDim, replReset)

	key, err := readHiddenAPIKey("Enter Astra API key (input hidden):")
	if err != nil || key == "" {
		fmt.Fprintf(os.Stderr, "%s⚠ Skipped — agent management tools won't work until ASTRA_API_KEY is set.%s\n", replDim, replReset)
		return ""
	}
	return key
}
