/**
 * forge key — manage API keys (service/agent credentials, incl. MCP).
 *
 *   forge key create [name] [--save]   mint a key
 *   forge key list                     list keys
 *   forge key revoke <id>              revoke a key
 *
 * Operates directly on the local key store (<dataDir>/api-keys.json) — running
 * the `forge` CLI already proves local filesystem access, so no admin password is
 * needed (the HTTP route still requires it; that's the remote/browser path). The
 * running server picks up changes on its next request (its key cache
 * self-invalidates on the file's mtime). Set FORGE_DATA_DIR to target a
 * non-default instance's data dir.
 */

import { writeFileSync, mkdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { createApiKey, listApiKeys, revokeApiKey } from '../lib/api-keys';

export async function keyCommand(args: string[]): Promise<void> {
  const sub = args[0];
  const positional = args.slice(1).filter((a) => !a.startsWith('--'));

  if (sub === 'list') {
    const keys = listApiKeys();
    if (!keys.length) { console.log('No API keys. Create one: forge key create <name>'); return; }
    for (const k of keys) {
      const used = k.lastUsedAt ? k.lastUsedAt.slice(0, 10) : 'never';
      console.log(`  ${k.id}  ${String(k.prefix).padEnd(20)} ${k.name}  (created ${k.createdAt?.slice(0, 10)}, last used ${used})`);
    }
    return;
  }

  if (sub === 'create') {
    const name = positional[0] || 'agent key';
    const { key } = createApiKey(name);
    console.log(`\n✓ API key created (${name}):\n\n  ${key}\n`);
    console.log('  Copy it now — it will not be shown again.');
    if (args.includes('--save')) {
      const dir = join(homedir(), '.forge');
      mkdirSync(dir, { recursive: true });
      const f = join(dir, 'mcp-key');
      writeFileSync(f, key, { mode: 0o600 });
      console.log(`  Saved to ${f} — forge mcp will read it automatically.`);
    } else {
      console.log('  Use it:  export FORGE_API_KEY=<key>   (or rerun with --save)');
    }
    return;
  }

  if (sub === 'revoke') {
    const id = positional[0];
    if (!id) { console.log('Usage: forge key revoke <id>'); process.exit(1); }
    console.log(revokeApiKey(id) ? `✓ Revoked key ${id}` : `Key ${id} not found`);
    return;
  }

  console.log(`forge key — manage API keys (service/agent credentials, incl. MCP)

  forge key create [name] [--save]   Mint a key (--save writes it to ~/.forge/mcp-key)
  forge key list                     List keys
  forge key revoke <id>              Revoke a key

  No admin password — operates on the local key store directly.
  Set FORGE_DATA_DIR to target a non-default instance.`);
}
