'use strict';

const DEFAULT_BASE_URLS = Object.freeze({
  openai: 'https://api.portkey.ai/v1',
  anthropic: 'https://api.portkey.ai',
});

function defaultPortkeyBaseUrl(providerType) {
  return DEFAULT_BASE_URLS[String(providerType || '').toLowerCase()] || DEFAULT_BASE_URLS.openai;
}

function normalizeHeaderMap(headers) {
  if (!headers || typeof headers !== 'object' || Array.isArray(headers)) return {};
  const out = {};
  for (const [key, value] of Object.entries(headers)) {
    if (!key || value == null || value === '') continue;
    out[String(key).toLowerCase()] = String(value);
  }
  return out;
}

function parseCustomHeaders(value) {
  if (!value) return {};
  if (typeof value === 'object' && !Array.isArray(value)) return normalizeHeaderMap(value);
  if (typeof value !== 'string') return {};
  try {
    const parsed = JSON.parse(value);
    return normalizeHeaderMap(parsed);
  } catch {}
  const out = {};
  for (const line of value.split(/\r?\n/)) {
    const idx = line.indexOf(':');
    if (idx <= 0) continue;
    const key = line.slice(0, idx).trim();
    const val = line.slice(idx + 1).trim();
    if (key && val) out[key.toLowerCase()] = val;
  }
  return out;
}

function isPortkeyBaseUrl(baseUrl) {
  return /(^|\.)portkey\.ai(?:\/|$)/i.test(String(baseUrl || ''));
}

function isPortkeyHeaders(headers) {
  const h = parseCustomHeaders(headers);
  return Boolean(
    h['x-portkey-api-key'] ||
    h['x-portkey-provider'] ||
    h['x-portkey-virtual-key'] ||
    h['x-portkey-config']
  );
}

function isPortkeyProviderConfig(config = {}) {
  return isPortkeyBaseUrl(config.baseUrl || config.base_url) || isPortkeyHeaders(config.customHeaders || config.custom_headers);
}

function buildPortkeyHeaders({
  apiKey,
  providerSlug,
  virtualKey,
  configId,
  traceId,
  metadata,
  headers,
} = {}) {
  const out = normalizeHeaderMap(headers);
  if (apiKey) out['x-portkey-api-key'] = String(apiKey).trim();
  if (providerSlug) out['x-portkey-provider'] = String(providerSlug).trim();
  if (virtualKey) out['x-portkey-virtual-key'] = String(virtualKey).trim();
  if (configId) out['x-portkey-config'] = String(configId).trim();
  if (traceId) out['x-portkey-trace-id'] = String(traceId).trim();
  if (metadata) {
    out['x-portkey-metadata'] = typeof metadata === 'string' ? metadata : JSON.stringify(metadata);
  }
  return out;
}

function connectionKind({ authMethod, baseUrl, customHeaders } = {}) {
  if (authMethod === 'claude_cli') return 'claude_cli';
  if (authMethod === 'codex_cli') return 'codex_cli';
  if (authMethod === 'oauth_proxy') return 'oauth_proxy';
  if (authMethod === 'gemini_cli') return 'gemini_cli';
  if (authMethod === 'devbox') return 'devbox';
  if (isPortkeyBaseUrl(baseUrl) || isPortkeyHeaders(customHeaders)) return 'portkey';
  return 'direct';
}

function connectionLabel(kind) {
  switch (kind) {
    case 'portkey': return 'Portkey';
    case 'claude_cli': return 'Claude CLI';
    case 'codex_cli': return 'Codex CLI';
    case 'oauth_proxy': return 'OAuth proxy';
    case 'gemini_cli': return 'Gemini CLI';
    case 'devbox': return 'Devbox';
    default: return 'Direct';
  }
}

function routeLabel(row = {}) {
  const providerName = row.provider_name || row.name || row.provider_type || row.type || 'Provider';
  const kind = connectionKind({
    authMethod: row.auth_method,
    baseUrl: row.base_url || row.baseUrl,
    customHeaders: row.custom_headers || row.customHeaders,
  });
  return `${providerName} · ${connectionLabel(kind)}`;
}

module.exports = {
  DEFAULT_BASE_URLS,
  defaultPortkeyBaseUrl,
  parseCustomHeaders,
  normalizeHeaderMap,
  isPortkeyBaseUrl,
  isPortkeyHeaders,
  isPortkeyProviderConfig,
  buildPortkeyHeaders,
  connectionKind,
  connectionLabel,
  routeLabel,
};
