import process from 'node:process'

export type LoginType = 'qq' | 'wx'

export const DEFAULT_LOGIN_TYPE: LoginType = 'qq'

type BrowserConfigInput = {
  headless?: boolean
  devtools?: boolean
  keepAlive?: boolean
  prewarm?: boolean
  slowMoMs?: number
}

type ResolveBrowserLaunchOptionsInput = {
  browserConfig?: BrowserConfigInput
  chromePath?: string
  nodeEnv?: string
  ci?: string
}

export type BrowserLaunchOptions = {
  headless: boolean
  devtools: boolean
  usesBundledChromium: boolean
  keepAlive: boolean
  prewarm: boolean
  slowMoMs: number
}

export type ViewportSize = {
  width: number
  height: number
}

export function resolveBrowserLaunchOptions(options: ResolveBrowserLaunchOptionsInput = {}): BrowserLaunchOptions {
  const browserConfig = options.browserConfig || {}
  const chromePath = options.chromePath || ''
  const nodeEnv = options.nodeEnv ?? process.env.NODE_ENV
  const ci = options.ci ?? process.env.CI
  const explicitHeadless = browserConfig.headless
  const explicitDevtools = browserConfig.devtools
  const explicitKeepAlive = browserConfig.keepAlive
  const explicitPrewarm = browserConfig.prewarm
  const explicitSlowMo = browserConfig.slowMoMs
  const isProductionLike = nodeEnv === 'production' || ci === '1'

  const headless = typeof explicitHeadless === 'boolean' ? explicitHeadless : isProductionLike

  const devtools = typeof explicitDevtools === 'boolean' ? explicitDevtools : !headless

  const slowMoMs = Number.isFinite(explicitSlowMo)
    ? Math.max(0, Math.min(explicitSlowMo, 2_000))
    : headless
      ? 0
      : 150

  const keepAlive = typeof explicitKeepAlive === 'boolean' ? explicitKeepAlive : !isProductionLike
  const prewarm = typeof explicitPrewarm === 'boolean' ? explicitPrewarm : keepAlive

  return {
    headless,
    devtools,
    usesBundledChromium: !chromePath,
    keepAlive,
    prewarm,
    slowMoMs,
  }
}

export function buildChromiumLaunchOptions(
  launchOptions: BrowserLaunchOptions,
  { chromePath = '' }: { chromePath?: string } = {},
) {
  const options = {
    headless: launchOptions.headless,
    devtools: launchOptions.devtools,
    slowMo: launchOptions.slowMoMs,
  }

  if (chromePath) {
    return {
      ...options,
      executablePath: chromePath,
    }
  }

  return options
}

export function resolveDefaultViewport(rawValue?: unknown): ViewportSize {
  const fromVncResolution = parseViewportSpec(rawValue)
  if (fromVncResolution) {
    return fromVncResolution
  }

  return { width: 1600, height: 900 }
}

export function parseViewportSpec(rawValue: unknown): ViewportSize | null {
  const text = String(rawValue || '').trim()

  if (!text) {
    return null
  }

  const match = text.match(/^(\d+)x(\d+)(?:x\d+)?$/i)
  if (!match) {
    return null
  }

  const width = Number(match[1])
  const height = Number(match[2])

  if (!Number.isFinite(width) || !Number.isFinite(height) || width < 800 || height < 600) {
    return null
  }

  return { width, height }
}

export function normalizeLoginType(value: unknown, fallback: LoginType = DEFAULT_LOGIN_TYPE): LoginType {
  const normalized = String(value || fallback).trim().toLowerCase()
  if (['qq', 'qc'].includes(normalized)) {
    return 'qq'
  }
  if (['wx', 'vx', 'wechat', 'weixin'].includes(normalized)) {
    return 'wx'
  }
  return fallback
}

export function getLoginTypeLabel(loginType: LoginType | string): string {
  return loginType === 'wx' ? '微信' : 'QQ'
}
