import { homedir } from 'node:os'
import { join } from 'node:path'

/** RiOS CLI: Anthropic-compatible env aliases + default gateway when using RIOS_* only */
const RIOS_DEFAULT_BASE_URL = 'https://mlm.rios.com.ai'

// Separate from official Claude Code: default config/state under ~/.rios-code instead of ~/.claude.
// Override with CLAUDE_CONFIG_DIR (e.g. CLAUDE_CONFIG_DIR=$HOME/.claude to intentionally share).
if (
  process.env.CLAUDE_CONFIG_DIR === undefined ||
  process.env.CLAUDE_CONFIG_DIR === ''
) {
  process.env.CLAUDE_CONFIG_DIR = join(homedir(), '.rios-code')
}

if (!process.env.ANTHROPIC_API_KEY && process.env.RIOS_API_KEY) {
  process.env.ANTHROPIC_API_KEY = process.env.RIOS_API_KEY;
}
if (!process.env.ANTHROPIC_AUTH_TOKEN && process.env.RIOS_AUTH_TOKEN) {
  process.env.ANTHROPIC_AUTH_TOKEN = process.env.RIOS_AUTH_TOKEN;
}
// 不设 ANTHROPIC_AUTH_TOKEN=RIOS_API_KEY：与 ANTHROPIC_API_KEY 重复会触发 CLI「Auth conflict」。
// RiOS 网关下由 client.ts 注入 Bearer（configureApiKeyHeaders + 订阅用户走 apiKey 而非 OAuth）。
if (!process.env.ANTHROPIC_BASE_URL && process.env.RIOS_BASE_URL) {
  process.env.ANTHROPIC_BASE_URL = process.env.RIOS_BASE_URL;
}
const usesRiosEnv = Boolean(
  process.env.RIOS_API_KEY || process.env.RIOS_AUTH_TOKEN || process.env.RIOS_BASE_URL,
);
if (!process.env.ANTHROPIC_BASE_URL && usesRiosEnv) {
  process.env.ANTHROPIC_BASE_URL = RIOS_DEFAULT_BASE_URL;
}

/** Mirrors `isRiOsGatewayAnthropicBaseUrl` in src/utils/model/providers.ts (preload stays dependency-light). */
function isRiOsGatewayAnthropicBaseUrlFromEnv(): boolean {
  const baseUrl = process.env.ANTHROPIC_BASE_URL
  if (!baseUrl) {
    return false
  }
  try {
    const hostname = new URL(baseUrl).hostname.toLowerCase()
    if (hostname === 'mlm.rios.com.ai') {
      return true
    }
    return hostname.endsWith('.rios.com.ai')
  } catch {
    return false
  }
}

if (
  !Object.prototype.hasOwnProperty.call(
    process.env,
    'RIOS_OAUTH_USE_CLOUD_CALLBACK',
  ) &&
  isRiOsGatewayAnthropicBaseUrlFromEnv()
) {
  process.env.RIOS_OAUTH_USE_CLOUD_CALLBACK = '1'
}

if (
  !process.env.CLAUDE_CODE_OAUTH_CLIENT_ID &&
  process.env.RIOS_OAUTH_CLIENT_ID
) {
  process.env.CLAUDE_CODE_OAUTH_CLIENT_ID = process.env.RIOS_OAUTH_CLIENT_ID
}

/** .env 示例占位符或未设置时，为 RiOS 网关填入编排器常见默认可用模型 */
function applyRiosGatewayDefaultModelsIfPlaceholder(): void {
  if (!isRiOsGatewayAnthropicBaseUrlFromEnv()) {
    return
  }
  const placeholder = /^your-model-id$/i
  const isUnsetOrPlaceholder = (v: string | undefined) => {
    const t = v?.trim() ?? ''
    return !t || placeholder.test(t)
  }
  const main = process.env.RIOS_DEFAULT_MODEL?.trim() || 'gpt-5.4-mini'
  const sonnet = process.env.RIOS_DEFAULT_SONNET_MODEL?.trim() || 'gpt-4o'
  const haiku = process.env.RIOS_DEFAULT_HAIKU_MODEL?.trim() || 'gpt-5.4-mini'
  const opus = process.env.RIOS_DEFAULT_OPUS_MODEL?.trim() || 'claude-3-5-sonnet-20241022'
  if (isUnsetOrPlaceholder(process.env.ANTHROPIC_MODEL)) {
    process.env.ANTHROPIC_MODEL = main
  }
  if (isUnsetOrPlaceholder(process.env.ANTHROPIC_DEFAULT_SONNET_MODEL)) {
    process.env.ANTHROPIC_DEFAULT_SONNET_MODEL = sonnet
  }
  if (isUnsetOrPlaceholder(process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL)) {
    process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL = haiku
  }
  if (isUnsetOrPlaceholder(process.env.ANTHROPIC_DEFAULT_OPUS_MODEL)) {
    process.env.ANTHROPIC_DEFAULT_OPUS_MODEL = opus
  }
}
applyRiosGatewayDefaultModelsIfPlaceholder()

const version = process.env.CLAUDE_CODE_LOCAL_VERSION ?? '0.2.0';
const packageUrl = process.env.CLAUDE_CODE_LOCAL_PACKAGE_URL ?? 'rios-cli';
const buildTime = process.env.CLAUDE_CODE_LOCAL_BUILD_TIME ?? new Date().toISOString();

process.env.CLAUDE_CODE_LOCAL_SKIP_REMOTE_PREFETCH ??= '1';

Object.assign(globalThis, {
  MACRO: {
    VERSION: version,
    PACKAGE_URL: packageUrl,
    NATIVE_PACKAGE_URL: packageUrl,
    BUILD_TIME: buildTime,
    FEEDBACK_CHANNEL: 'local',
    VERSION_CHANGELOG: '',
    ISSUES_EXPLAINER: '',
  },
});
