import type { Command } from 'commander';
import readline from 'readline';
import {
  loadStoredAnthropicAuth,
  loadStoredAnthropicAuthToken,
  storeAnthropicAuth,
  storeAnthropicAuthToken,
} 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 registerAnthropicAuthCommand(program: Command): void {
  program
    .command('anthropic-auth')
    .description('Store an Anthropic API key or auth token (auth.json)')
    .option('--token', 'Store an Anthropic auth token instead of an API key')
    .action(async (opts: { token?: boolean }) => {

      if (opts.token) {
        if (loadStoredAnthropicAuthToken()) {
          console.log('Anthropic auth token already exists.');
          console.log('Delete ~/.config/flynn/auth.json anthropic.auth_token entry if you want to re-authenticate.');
          process.exit(0);
        }
      } else {
        const existing = loadStoredAnthropicAuth();
        if (existing?.api_key) {
          console.log('Anthropic API key already exists.');
          console.log('Delete ~/.config/flynn/auth.json anthropic.api_key entry if you want to re-authenticate.');
          process.exit(0);
        }
      }

      console.log('Anthropic uses API keys for authentication.');
      console.log('Create a key at: https://console.anthropic.com/settings/keys');
      console.log('');

      try {
        if (opts.token) {
          const token = await promptHidden('Enter Anthropic auth token: ');
          storeAnthropicAuthToken(token);
        } else {
          const apiKey = await promptHidden('Enter Anthropic API key: ');
          storeAnthropicAuth(apiKey);
        }
        console.log('');
        console.log('Anthropic credential stored in ~/.config/flynn/auth.json');
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`Anthropic auth failed: ${message}`);
        process.exit(1);
      }
    });
}
