package main

import (
	"bufio"
	"fmt"
	"strconv"
	"strings"
)

// promptInt reads an integer in [min, max] from the reader, re-prompting on bad input.
func promptInt(in *bufio.Reader, prompt string, min, max int) (int, error) {
	for {
		fmt.Print(prompt)
		line, err := in.ReadString('\n')
		if err != nil {
			return 0, fmt.Errorf("read input: %w", err)
		}
		n, err := strconv.Atoi(strings.TrimSpace(line))
		if err != nil || n < min || n > max {
			fmt.Printf("  Enter a number between %d and %d\n", min, max)
			continue
		}
		return n, nil
	}
}

// promptString reads a line, returning defaultVal when the user presses Enter with no input.
func promptString(in *bufio.Reader, prompt, defaultVal string) (string, error) {
	fmt.Print(prompt)
	line, err := in.ReadString('\n')
	if err != nil {
		return "", fmt.Errorf("read input: %w", err)
	}
	if s := strings.TrimSpace(line); s != "" {
		return s, nil
	}
	return defaultVal, nil
}

// promptBool reads a y/N confirmation, returning defaultVal on empty input.
func promptBool(in *bufio.Reader, prompt string, defaultVal bool) (bool, error) {
	hint := "y/N"
	if defaultVal {
		hint = "Y/n"
	}
	fmt.Printf("%s [%s]: ", prompt, hint)
	line, err := in.ReadString('\n')
	if err != nil {
		return false, fmt.Errorf("read input: %w", err)
	}
	switch strings.ToLower(strings.TrimSpace(line)) {
	case "y", "yes":
		return true, nil
	case "n", "no":
		return false, nil
	default:
		return defaultVal, nil
	}
}
