'use strict';

const fs = require('fs');
const path = require('path');
const { parseCustomHeaders } = require('../llm/portkey');

function readDevboxClaudeAuthHeaders({ home = process.env.HOME, fsImpl = fs } = {}) {
  if (!home) return null;
  const authFile = path.join(home, '.devbox', 'secrets', 'claude', 'auth_headers');
  const raw = fsImpl.readFileSync(authFile, 'utf8').trim();
  if (!raw) return null;
  const headers = parseCustomHeaders(raw);
  if (!Object.keys(headers).length) return null;
  return { authFile, raw, headers };
}

function maskSecret(value) {
  const text = String(value || '');
  if (!text) return '';
  if (text.length <= 12) return text.slice(0, 3) + '...';
  return text.slice(0, 8) + '...' + text.slice(-4);
}

function normalizeDevboxBaseUrl(value) {
  const url = String(value || '').trim().replace(/\/+$/, '');
  if (!/^https?:\/\//i.test(url)) return '';
  return /\/v\d+$/i.test(url) ? url : `${url}/v1`;
}

function detectDevboxClaudeBaseUrl({ env = process.env, home = env.HOME, fsImpl = fs } = {}) {
  const envUrl = normalizeDevboxBaseUrl(env.ANTHROPIC_BASE_URL);
  if (envUrl) return envUrl;

  if (home) {
    try {
      const claudeScript = fsImpl.readFileSync(path.join(home, '.devbox', 'ai', 'claude', 'claude'), 'utf8');
      const vpnMatch = claudeScript.match(/VPN_CHECK_URL="(https?:\/\/[^"]+)"/);
      const scriptUrl = normalizeDevboxBaseUrl(vpnMatch && vpnMatch[1]);
      if (scriptUrl) return scriptUrl;
    } catch {}

    try {
      const logFile = path.join(home, '.devbox', 'logs', 'devbox-logs.log');
      const log = fsImpl.readFileSync(logFile, 'utf8');
      const matches = Array.from(log.matchAll(/ANTHROPIC_BASE_URL:\s*(https?:\/\/[^\s"}]+)/g));
      const last = matches.length ? normalizeDevboxBaseUrl(matches[matches.length - 1][1]) : '';
      if (last) return last;
    } catch {}
  }

  return '';
}

function getDevboxClaudePortkeyGateway({ home = process.env.HOME, fsImpl = fs, env = process.env } = {}) {
  try {
    const auth = readDevboxClaudeAuthHeaders({ home, fsImpl });
    const headers = auth && auth.headers;
    const apiKey = headers && headers['x-portkey-api-key'];
    if (!apiKey) return null;
    return {
      source: 'devbox-claude-auth-headers',
      name: 'Portkey gateway',
      label: 'devbox',
      apiKey,
      apiKeyMasked: maskSecret(apiKey),
      customHeaders: headers,
      hasProvider: Boolean(headers['x-portkey-provider']),
      hasVirtualKey: Boolean(headers['x-portkey-virtual-key']),
      hasConfig: Boolean(headers['x-portkey-config']),
      hasMetadata: Boolean(headers['x-portkey-metadata']),
      baseUrl: detectDevboxClaudeBaseUrl({ env, home, fsImpl }),
    };
  } catch {
    return null;
  }
}

function configureDevboxGateway({ env = process.env, home = env.HOME, logger = console } = {}) {
  // Auto-detect corporate Claude Code gateway if not already configured. The
  // devbox `claude` wrapper stores auth headers on disk but only injects them
  // when running `claude` directly.
  const hasRealKey = env.ANTHROPIC_API_KEY && env.ANTHROPIC_API_KEY !== 'sk-ant-api03-unused';
  if (env.ANTHROPIC_CUSTOM_HEADERS_B64 || hasRealKey || !home) return false;

  try {
    const auth = readDevboxClaudeAuthHeaders({ home });
    const headers = auth && auth.raw;
    if (!headers) return false;

    env.ANTHROPIC_CUSTOM_HEADERS_B64 = Buffer.from(headers).toString('base64');
    if (!env.ANTHROPIC_CUSTOM_HEADERS) env.ANTHROPIC_CUSTOM_HEADERS = headers;
    if (!env.ANTHROPIC_AUTH_TOKEN) env.ANTHROPIC_AUTH_TOKEN = 'sk-ant-api03-unused';

    if (!env.ANTHROPIC_BASE_URL) {
      const baseUrl = detectDevboxClaudeBaseUrl({ env, home });
      if (baseUrl) env.ANTHROPIC_BASE_URL = baseUrl;
    }

    try { require('../compat').recordCompatUsage('devbox_gateway'); } catch {}
    if (logger && logger.log) logger.log('[brain] Auto-detected devbox Claude gateway auth');
    return true;
  } catch {
    return false;
  }
}

module.exports = {
  configureDevboxGateway,
  detectDevboxClaudeBaseUrl,
  getDevboxClaudePortkeyGateway,
  readDevboxClaudeAuthHeaders,
};
