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

async function promptHidden(question: string): Promise<string> {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
  const rlAny = rl as unknown as { stdoutMuted?: boolean; _writeToOutput?: (s: string) => void };
  rlAny.stdoutMuted = true;

  rlAny._writeToOutput = (s: string) => {
    if (!rlAny.stdoutMuted) {
      process.stdout.write(s);
      return;
    }
    if (s.includes('\n')) {
      process.stdout.write('\n');
    } else {
      process.stdout.write('*');
    }
  };

  const answer = await new Promise<string>((resolve) => rl.question(question, resolve));
  rlAny.stdoutMuted = false;
  rl.close();
  process.stdout.write('\n');
  return answer.trim();
}

export function registerOpenaiKeyCommand(program: Command): void {
  program
    .command('openai-key')
    .description('Store an OpenAI API key (auth.json)')
    .action(async () => {
      const existing = loadStoredOpenAIApiKey();
      if (existing) {
        console.log('OpenAI API key already exists.');
        console.log('Delete ~/.config/flynn/auth.json openai.api_key entry if you want to re-authenticate.');
        process.exit(0);
      }

      console.log('OpenAI uses API keys for standard API access.');
      console.log('Create a key at: https://platform.openai.com/api-keys');
      console.log('');

      try {
        const apiKey = await promptHidden('Enter OpenAI API key: ');
        storeOpenAIApiKey(apiKey);
        console.log('');
        console.log('OpenAI API key stored in ~/.config/flynn/auth.json');
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`OpenAI API key storage failed: ${message}`);
        process.exit(1);
      }
    });
}
