import { createInterface } from 'node:readline';

/**
 * Read email + password as two lines from non-TTY stdin (the headless dual
 * path for callers that cannot pass argv: printf 'email\npassword\n' | …).
 * Caller gates on !isTTY; the password line is kept as-is (no trim —
 * whitespace may be intentional).
 *
 * Separate module (not login.ts) so tests can exercise the REAL reader
 * against real streams while token-ops specs mock this seam cleanly.
 */
export function readCredentialsFromPipedStdin(
  input: NodeJS.ReadableStream = process.stdin,
): Promise<{ email: string | null; password: string | null }> {
  return new Promise((resolve) => {
    const lines: string[] = [];
    const rl = createInterface({ input });
    rl.on('line', (l) => {
      lines.push(l);
      if (lines.length >= 2) rl.close();
    });
    rl.on('close', () => {
      resolve({ email: (lines[0] ?? '').trim() || null, password: lines[1] ?? null });
    });
  });
}
