import type { EnvReader } from '#cli/core/env'
import type {
  RunConfig,
  ToolApprovalsMode,
} from '#cli/core/model'
import { createEnvReader } from '#cli/core/env'
import { resolveModelQuirkOverrides } from '#cli/core/model-quirks'
import {
  inferBuiltinModelContextWindow,
  LEGACY_DEFAULT_CONTEXT_WINDOW,
} from '#cli/compat/providers'

export type { EnvReader }
export { createEnvReader }

export function resolveInitialApprovalMode(env: EnvReader): ToolApprovalsMode {
  const raw = env.prefixedStr('TOOL_APPROVALS').toLowerCase()
  if (!raw)
    return env.prefixedBool('SKIP_APPROVAL') ? 'auto' : 'normal'
  if (raw === 'auto' || raw === 'all' || raw === 'always')
    return 'auto'
  if (raw === 'strict' || raw === 'manual')
    return 'strict'
  return 'normal'
}

export function resolveInitialRunConfig(env: EnvReader): RunConfig {
  const model = env.prefixedStr('MODEL') || 'deepseek-v3.1'
  const overrides = resolveModelQuirkOverrides(model)
  const temperature
    = typeof overrides?.temperature === 'number'
      ? overrides.temperature
      : (env.prefixedFloat('TEMPERATURE') ?? 0.7)
  const interleaved_thinking
    = typeof overrides?.interleavedThinking === 'boolean'
      ? overrides.interleavedThinking
      : (env.prefixedBool('INTERLEAVED_THINKING') ?? false)
  const explicitContextWindow = env.prefixedInt('CONTEXT_WINDOW')
  const inferredContextWindow = inferBuiltinModelContextWindow(model)
  return {
    model,
    context_window:
      explicitContextWindow
      || inferredContextWindow
      || LEGACY_DEFAULT_CONTEXT_WINDOW,
    temperature,
    interleaved_thinking,
  }
}

export function resolveInitialSessionId(env: EnvReader): string {
  return env.prefixedStr('SESSION_ID') || ''
}

export function resolveStreamTimeouts(
  env: EnvReader,
): Readonly<{ idleMs: number, totalMs: number }> {
  return {
    idleMs: env.prefixedInt('STREAM_IDLE_TIMEOUT_MS') ?? 30 * 60_000,
    totalMs: env.prefixedInt('STREAM_TOTAL_TIMEOUT_MS') ?? 90 * 60_000,
  } as const
}
