import type { DimSdkStore } from '#cli/core/store'
import { resolveModelQuirkOverrides } from '#cli/core/model-quirks'

type RuntimeGlobals = typeof globalThis & {
  open?: (url?: string | URL, target?: string, features?: string) => unknown
  process?: NodeJS.Process
}

type OAuthRuntimeStore = Pick<DimSdkStore, 'setEnvVar' | 'state'>

function runtimeGlobals(): RuntimeGlobals {
  return globalThis as RuntimeGlobals
}

export function getRuntimeEnv(): Record<string, string | undefined> {
  return runtimeGlobals().process?.env ?? {}
}

export function normalizeUrl(value: unknown): string {
  return String(value ?? '')
    .trim()
    .replace(/\/+$/, '')
}

export function resolveActiveOpenAiBaseUrl(
  store: Pick<OAuthRuntimeStore, 'state'> | undefined,
  env: Record<string, string | undefined>,
): string {
  return normalizeUrl(
    store?.state.config?.baseUrl ??
      env.DIMCODE_OPENAI_BASE_URL ??
      env.OPENAI_BASE_URL ??
      '',
  )
}

export async function openOAuthBrowserUrl(
  url: string,
  nodeLike?: boolean,
): Promise<boolean> {
  if (!url) return false

  if (!nodeLike) {
    try {
      const opener = runtimeGlobals().open
      if (typeof opener === 'function') {
        opener(url, '_blank', 'noopener,noreferrer')
        return true
      }
    } catch {}
    return false
  }

  try {
    const { spawn } = await import('node:child_process')
    const platform = String(runtimeGlobals().process?.platform ?? '')
    if (platform === 'win32') {
      spawn('cmd', ['/c', 'start', '', url], {
        shell: false,
        detached: true,
        stdio: 'ignore',
      }).unref()
      return true
    }
    const cmd = platform === 'darwin' ? 'open' : 'xdg-open'
    spawn(cmd, [url], { shell: false, detached: true, stdio: 'ignore' }).unref()
    return true
  } catch {
    return false
  }
}

export function applyOAuthModelQuirks(
  opts: Readonly<{
    modelId: string
    store?: OAuthRuntimeStore
    nodeLike?: boolean
  }>,
): void {
  const modelId = String(opts.modelId ?? '').trim()
  if (!modelId) return

  const quirks = resolveModelQuirkOverrides(modelId)
  if (opts.store) {
    if (typeof quirks?.temperature === 'number') {
      opts.store.state.config.temperature = quirks.temperature
      opts.store.setEnvVar('DIMCODE_TEMPERATURE', String(quirks.temperature))
    }
    if (typeof quirks?.interleavedThinking === 'boolean') {
      opts.store.state.config.interleaved_thinking = quirks.interleavedThinking
      const flag = quirks.interleavedThinking ? '1' : '0'
      opts.store.setEnvVar('DIMCODE_INTERLEAVED_THINKING', flag)
    }
    return
  }

  if (!opts.nodeLike) return
  const proc = runtimeGlobals().process
  if (!proc?.env) return

  if (typeof quirks?.temperature === 'number') {
    proc.env.DIMCODE_TEMPERATURE = String(quirks.temperature)
  }
  if (typeof quirks?.interleavedThinking === 'boolean') {
    const flag = quirks.interleavedThinking ? '1' : '0'
    proc.env.DIMCODE_INTERLEAVED_THINKING = flag
  }
}
