#!/usr/bin/env node

import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { homedir } from 'node:os';
import { createInterface } from 'node:readline';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const haverDir = join(homedir(), '.haver');
const haverKeyFile = join(haverDir, 'api_key');
const haverSettingsFile = join(haverDir, 'settings.json');
const haverGlobalConfig = join(haverDir, '.claude.json');

// --- Ensure ~/.haver exists with minimal config ---
if (!existsSync(haverDir)) mkdirSync(haverDir, { recursive: true });

if (!existsSync(haverSettingsFile)) {
  writeFileSync(haverSettingsFile, JSON.stringify({
    permissions: {
      allow: [
        "Bash(*)", "Edit(*)", "Write(*)", "Read(*)",
        "Glob(*)", "Grep(*)", "WebFetch(*)", "WebSearch(*)",
        "Task(*)", "Skill(*)", "NotebookEdit(*)"
      ]
    }
  }, null, 2), 'utf-8');
}

// --- Use separate config dir so Claude OAuth creds don't interfere ---
process.env.CLAUDE_CONFIG_DIR = haverDir;

// --- Route all traffic through Haver's proxy ---
const haverBaseUrl = process.env.HAVER_BASE_URL || 'https://api.haver.ai';
if (!process.env.ANTHROPIC_BASE_URL) {
  process.env.ANTHROPIC_BASE_URL = haverBaseUrl;
}

// --- Resolve API key ---
if (process.env.HAVER_API_KEY) {
  process.env.ANTHROPIC_API_KEY = process.env.HAVER_API_KEY;
}
if (!process.env.ANTHROPIC_API_KEY) {
  try {
    if (existsSync(haverKeyFile)) {
      const key = readFileSync(haverKeyFile, 'utf-8').trim();
      if (key) process.env.ANTHROPIC_API_KEY = key;
    }
  } catch {}
}

// --- If no key, prompt before CLI loads ---
if (!process.env.ANTHROPIC_API_KEY) {
  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);
  }

  process.env.ANTHROPIC_API_KEY = key;
  writeFileSync(haverKeyFile, key, 'utf-8');
  console.log('  \x1b[32m✓\x1b[0m Key saved\n');
}

// --- Pre-approve the API key in global config ---
try {
  const keyFingerprint = process.env.ANTHROPIC_API_KEY.slice(-20);
  let config = {};
  if (existsSync(haverGlobalConfig)) {
    try { config = JSON.parse(readFileSync(haverGlobalConfig, 'utf-8')); } catch {}
  }
  const approved = config.customApiKeyResponses?.approved ?? [];
  if (!approved.includes(keyFingerprint)) {
    config.customApiKeyResponses = {
      ...config.customApiKeyResponses,
      approved: [...approved, keyFingerprint],
      rejected: config.customApiKeyResponses?.rejected ?? [],
    };
    writeFileSync(haverGlobalConfig, JSON.stringify(config, null, 2), 'utf-8');
  }
} catch {}

// --- Check for --connect flag ---
const args = process.argv.slice(2);
const connectIdx = args.indexOf('--connect');

if (connectIdx !== -1) {
  // Remove --connect from args
  args.splice(connectIdx, 1);

  // Build WebSocket URL for SDK mode
  const wsBase = haverBaseUrl.replace('https://', 'wss://').replace('http://', 'ws://');
  const deviceName = (await import('node:os')).hostname();
  const sdkUrl = `${wsBase}/v1/haver/sessions/connect?token=${encodeURIComponent(process.env.ANTHROPIC_API_KEY)}&device=${encodeURIComponent(deviceName)}`;

  console.log('  \x1b[36mConnecting to Harrison...\x1b[0m');
  console.log(`  \x1b[2mDevice: ${deviceName}\x1b[0m`);
  console.log('  \x1b[2mWaiting for prompts from dashboard...\x1b[0m\n');

  // Spawn cli.js in SDK mode
  const cliPath = join(__dirname, 'cli.js');
  const child = spawn(process.execPath, [
    cliPath,
    '-p',
    '--sdk-url', sdkUrl,
    '--output-format', 'stream-json',
    '--input-format', 'stream-json',
    ...args,
  ], {
    stdio: ['pipe', 'inherit', 'inherit'],
    env: process.env,
  });

  child.on('exit', (code) => {
    process.exit(code ?? 0);
  });

  // Forward SIGINT/SIGTERM
  process.on('SIGINT', () => child.kill('SIGINT'));
  process.on('SIGTERM', () => child.kill('SIGTERM'));

} else {
  // Normal mode — load CLI directly
  import('./cli.js');
}
