import type { Command } from 'commander';
import readline from 'readline';
import { loadStoredGeminiAuth, storeGeminiAuth } 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();
}

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 registerGeminiAuthCommand(program: Command): void {
  program
    .command('gemini-auth')
    .description('Store a Gemini API key (auth.json)')
    .action(async () => {
      const existing = loadStoredGeminiAuth();
      if (existing?.api_key) {
        console.log('Gemini API key already exists.');
        const confirmed = await promptYesNo('Re-authenticate and replace it? (y/N): ');
        if (!confirmed) {
          console.log('Cancelled.');
          process.exit(0);
        }
      }

      console.log('Gemini uses API keys for direct API access.');
      console.log('Create a key at: https://aistudio.google.com/apikey');
      console.log('');

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