import type { Command } from 'commander';
import readline from 'readline';
import {
  loadStoredAnthropicAuth,
  loadStoredAnthropicAuthToken,
  storeAnthropicAuth,
  storeAnthropicAuthToken,
} from '../auth/index.js';

type AnthropicAuthMode = 'api' | 'token';

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';
}

function parseAnthropicAuthMode(value: string): AnthropicAuthMode {
  const mode = value.trim().toLowerCase();
  if (mode === 'api' || mode === 'token') {
    return mode;
  }
  throw new Error(`Invalid mode "${value}". Expected: api or token.`);
}

function resolveAuthMode(opts: { token?: boolean; mode?: AnthropicAuthMode }): AnthropicAuthMode {
  if (opts.mode) {
    if (opts.token && opts.mode !== 'token') {
      throw new Error('Conflicting options: --token implies --mode token, but --mode api was provided.');
    }
    return opts.mode;
  }
  if (opts.token) {
    return 'token';
  }
  return 'api';
}

export function registerAnthropicAuthCommand(program: Command): void {
  program
    .command('anthropic-auth')
    .description('Store an Anthropic API key or auth token (auth.json)')
    .option('--mode <mode>', 'Credential mode: api or token', parseAnthropicAuthMode)
    .option('--token', 'Store an Anthropic auth token instead of an API key')
    .action(async (opts: { token?: boolean; mode?: AnthropicAuthMode }) => {
      const mode = resolveAuthMode(opts);

      if (mode === 'token') {
        if (loadStoredAnthropicAuthToken()) {
          console.log('Anthropic auth token already exists.');
          const confirmed = await promptYesNo('Re-authenticate and replace it? (y/N): ');
          if (!confirmed) {
            console.log('Cancelled.');
            process.exit(0);
          }
        }
      } else {
        const existing = loadStoredAnthropicAuth();
        if (existing?.api_key) {
          console.log('Anthropic 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('Anthropic uses API keys for authentication.');
      console.log('Create a key at: https://console.anthropic.com/settings/keys');
      console.log('');

      try {
        if (mode === '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);
      }
    });
}
