import { createInterface } from "node:readline";

// Single shared interface — exported so module setup functions can use it directly.
export const rl = createInterface({ input: process.stdin, output: process.stdout });

function ask(prompt) {
  return new Promise(resolve => rl.question(prompt, resolve));
}

export async function askText(question, defaultValue = "", configValue = undefined) {
  if (configValue !== undefined) {
    console.log(`${question}: ${configValue} (from config)`);
    return String(configValue);
  }
  const display = defaultValue ? `${question} [${defaultValue}]: ` : `${question}: `;
  const answer = await ask(display);
  return answer.trim() || defaultValue;
}

export async function askYesNo(question, defaultYes = true, configValue = undefined) {
  if (configValue !== undefined) {
    const val = Boolean(configValue);
    console.log(`${question}: ${val ? "yes" : "no"} (from config)`);
    return val;
  }
  const hint = defaultYes ? "Y/n" : "y/N";
  const answer = await ask(`${question} [${hint}]: `);
  const v = answer.trim().toLowerCase();
  if (!v) return defaultYes;
  return v === "y" || v === "yes";
}

export async function askChoice(question, choices, configValue = undefined) {
  if (configValue !== undefined) {
    console.log(`\n${question}\n  → ${configValue} (from config)`);
    return configValue;
  }
  while (true) {
    process.stdout.write(`\n${question}\n`);
    choices.forEach((c, i) => process.stdout.write(`  ${i + 1}. ${c}\n`));
    const answer = await ask(`Choice (1-${choices.length}): `);
    const n = parseInt(answer.trim(), 10);
    if (n >= 1 && n <= choices.length) return choices[n - 1];
    process.stdout.write(`Please enter a number between 1 and ${choices.length}.\n`);
  }
}

export async function askMultiSelect(question, choices, configValue = undefined) {
  if (choices.length === 0) return [];
  if (configValue !== undefined) {
    console.log(`\n${question}\n  → ${configValue.length ? configValue.join(", ") : "(none)"} (from config)`);
    return configValue;
  }
  while (true) {
    process.stdout.write(`\n${question}\n`);
    choices.forEach((c, i) => process.stdout.write(`  ${i + 1}. ${c}\n`));
    process.stdout.write("  0. All\n");
    const answer = await ask("Enter numbers separated by commas (0=all, Enter=skip all): ");
    const trimmed = answer.trim();
    if (!trimmed) return [];
    if (trimmed === "0") return [...choices];
    const parts = trimmed.split(",").map(s => parseInt(s.trim(), 10));
    if (parts.every(n => !isNaN(n) && n >= 1 && n <= choices.length)) {
      return parts.map(n => choices[n - 1]);
    }
    process.stdout.write(`Invalid selection — enter numbers 1-${choices.length}, comma-separated.\n`);
  }
}
