import { color } from "./formatter";

export async function confirm(message: string, defaultValue = false): Promise<boolean> {
  const hint = defaultValue ? "[Y/n]" : "[y/N]";
  process.stdout.write(`${message} ${color(hint, "gray")} `);
  
  for await (const line of console) {
    const answer = line.trim().toLowerCase();
    if (answer === "") return defaultValue;
    if (answer === "y" || answer === "yes") return true;
    if (answer === "n" || answer === "no") return false;
    
    process.stdout.write(`Please answer yes or no. ${message} ${color(hint, "gray")} `);
  }
  
  return defaultValue;
}

export async function prompt(question: string, defaultValue?: string): Promise<string> {
  const hint = defaultValue ? color(`[${defaultValue}]`, "gray") : "";
  process.stdout.write(`${question} ${hint} `);
  
  for await (const line of console) {
    const answer = line.trim();
    if (answer === "" && defaultValue) return defaultValue;
    if (answer !== "") return answer;
    
    process.stdout.write(`${question} ${hint} `);
  }
  
  return defaultValue || '';
}

export async function select(question: string, choices: { label: string; value: string }[]): Promise<string> {
  console.log(question);
  
  choices.forEach((choice, index) => {
    console.log(`  ${color(String(index + 1), "cyan")}. ${choice.label}`);
  });
  
  const maxChoice = choices.length;
  const answer = await prompt(`\nSelect (1-${maxChoice}):`);
  const index = parseInt(answer) - 1;
  
  if (index >= 0 && index < maxChoice && choices[index]) {
    return choices[index].value;
  }
  
  console.log(color('Invalid selection. Please try again.', 'red'));
  return select(question, choices);
}