import { afterEach, describe, expect, it } from 'vitest'
import {
  createEnvReader,
  ensurePrefixedEnvValue,
  readPrefixedEnvFlag,
  readProcessEnv,
  setPrefixedEnvValue,
} from '../src/dimsdk/core/env.ts'

const realProcess = globalThis.process

function setProcessEnv(env: Record<string, string | undefined>): void {
  Object.defineProperty(globalThis, 'process', {
    configurable: true,
    value: {
      ...realProcess,
      env,
    },
  })
}

afterEach(() => {
  Object.defineProperty(globalThis, 'process', {
    configurable: true,
    value: realProcess,
  })
})

describe('core env helpers', () => {
  it('reads process env through the typed runtime bridge', () => {
    setProcessEnv({
      DIMCODE_MODEL: 'gpt-5',
    })

    expect(readProcessEnv()).toEqual({
      DIMCODE_MODEL: 'gpt-5',
    })
  })

  it('resolves prefixed and alias values from merged env records', () => {
    const env = createEnvReader(
      {
        DIMCODE_CONTEXT_WINDOW: '8192',
      },
      {
        OPENAI_BASE_URL: 'https://fallback.example.com',
        ENABLED: 'true',
      },
    )

    expect(env.prefixedInt('CONTEXT_WINDOW')).toBe(8192)
    expect(env.str('DIMCODE_OPENAI_BASE_URL', 'OPENAI_BASE_URL')).toBe(
      'https://fallback.example.com',
    )
    expect(env.boolAny(['DISABLED', 'ENABLED'])).toBe(true)
  })

  it('sets and ensures prefixed env values without extra fallbacks', () => {
    const env: Record<string, string | undefined> = {}

    setPrefixedEnvValue(env, 'MODEL', ' gpt-5 ')
    expect(env.DIMCODE_MODEL).toBe('gpt-5')

    setPrefixedEnvValue(env, 'MODEL', '   ')
    expect(env.DIMCODE_MODEL).toBeUndefined()

    expect(ensurePrefixedEnvValue(env, 'LANG', 'zh-CN')).toBe('zh-CN')
    expect(env.DIMCODE_LANG).toBe('zh-CN')
    expect(readPrefixedEnvFlag(env, 'LANG')).toBe('zh-cn')
  })
})
