import type { Command } from 'commander';
import readline from 'readline';
import { loadStoredOpenAIAuth, loginOpenAI } from '../auth/index.js';

async function promptYesNo(question: string): Promise<boolean> {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
  const answer = await new Promise<string>((resolve) => rl.question(question, resolve));
  rl.close();
  const normalized = answer.trim().toLowerCase();
  return normalized === 'y' || normalized === 'yes';
}

export function registerOpenaiAuthCommand(program: Command): void {
  program
    .command('openai-auth')
    .description('Authenticate OpenAI (ChatGPT Plus/Pro) via OAuth device flow')
    .action(async () => {
      const existing = loadStoredOpenAIAuth();
      if (existing) {
        console.log('OpenAI OAuth token already exists.');
        const confirmed = await promptYesNo('Re-authenticate and replace it? (y/N): ');
        if (!confirmed) {
          console.log('Cancelled.');
          process.exit(0);
        }
      }

      console.log('Starting OpenAI OAuth device flow...');
      console.log('');

      try {
        await loginOpenAI((userCode, verificationUri) => {
          console.log(`Please visit: ${verificationUri}`);
          console.log(`Enter code:  ${userCode}`);
          console.log('');
          console.log('Waiting for authorization...');
        });

        console.log('');
        console.log('OpenAI authentication successful! Token stored.');
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`OpenAI login failed: ${message}`);
        process.exit(1);
      }
    });
}
