#!/usr/bin/env node

import { createInterface } from 'node:readline';

// Set default base URL to Haver AI platform
if (!process.env.ANTHROPIC_BASE_URL) {
  process.env.ANTHROPIC_BASE_URL = 'https://api.haver.ai';
}

// Support HAVER_API_KEY as the primary env var
if (process.env.HAVER_API_KEY) {
  process.env.ANTHROPIC_API_KEY = process.env.HAVER_API_KEY;
}

// If no API key is set at all, prompt for the Haver API key
if (!process.env.ANTHROPIC_API_KEY) {
  // Check if there are existing Claude Code credentials (OAuth token)
  let hasClaudeCredentials = false;
  try {
    const { existsSync, readFileSync } = await import('node:fs');
    const { join } = await import('node:path');
    const { homedir } = await import('node:os');
    const credFile = join(homedir(), '.claude', '.credentials.json');
    if (existsSync(credFile)) {
      const data = JSON.parse(readFileSync(credFile, 'utf-8'));
      if (data.claudeAiOauth?.accessToken) {
        hasClaudeCredentials = true;
      }
    }
  } catch {}

  if (!hasClaudeCredentials) {
    console.log('');
    console.log('  \x1b[1mHaver Code\x1b[0m');
    console.log('');
    console.log('  Get your API key from \x1b[36mhttps://harrison.haver.ai/api-keys\x1b[0m');
    console.log('');

    const key = await new Promise((resolve) => {
      const rl = createInterface({ input: process.stdin, output: process.stdout });
      rl.question('  \x1b[1mHaver API Key:\x1b[0m ', (answer) => {
        rl.close();
        resolve(answer.trim());
      });
    });

    if (!key) {
      console.log('\n  No key provided. Exiting.\n');
      process.exit(1);
    }

    if (key.startsWith('hs-')) {
      process.env.ANTHROPIC_API_KEY = key;
      console.log('  \x1b[32m✓\x1b[0m Key accepted\n');
    } else {
      // Might be an Anthropic API key — let it through
      process.env.ANTHROPIC_API_KEY = key;
    }
  }
}

// Load the main CLI
import('./cli.js');
