import type { Command } from 'commander';
import readline from 'readline';
import { loadStoredZaiAuth, storeZaiAuth } 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;
    }
    // Mask input characters, but preserve newlines.
    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 registerZaiAuthCommand(program: Command): void {
  program
    .command('zai-auth')
    .description('Store a Z.AI API key for the zhipuai provider (auth.json)')
    .action(async () => {
      const existing = loadStoredZaiAuth();
      if (existing) {
        console.log('Z.AI credential already exists.');
        console.log('Delete ~/.config/flynn/auth.json zai/zhipuai entry if you want to re-authenticate.');
        process.exit(0);
      }

      console.log('Z.AI uses API keys (HTTP Bearer), not an OAuth device flow.');
      console.log('Create a key at: https://z.ai/manage-apikey/apikey-list');
      console.log('');

      try {
        const apiKey = await promptHidden('Enter Z.AI API key: ');
        storeZaiAuth(apiKey);
        console.log('');
        console.log('Z.AI credential stored in ~/.config/flynn/auth.json');
        console.log('');
        console.log('Tip: For GLM Coding Plan set model endpoint to: https://api.z.ai/api/coding/paas/v4');
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`Z.AI auth failed: ${message}`);
        process.exit(1);
      }
    });
}
