import { afterEach, describe, expect, it } from 'vitest'
import {
  formatCwdDisplay,
  tildifyPath,
} from '../src/dimsdk/pages/utils/cwd-display.ts'
import {
  getProcessCwd,
  isNodeLike,
} from '../src/dimsdk/pages/utils/runtime.ts'

const realProcess = globalThis.process

function setProcess(value: NodeJS.Process | undefined): void {
  Object.defineProperty(globalThis, 'process', {
    configurable: true,
    value,
  })
}

afterEach(() => {
  setProcess(realProcess)
})

describe('runtime helpers', () => {
  it('detects node-like runtimes from the process shape', () => {
    setProcess({
      cwd: () => '/repo',
      versions: { node: '22.0.0' },
    } as unknown as NodeJS.Process)

    expect(isNodeLike()).toBe(true)

    setProcess({
      cwd: () => '/repo',
      versions: {},
    } as unknown as NodeJS.Process)

    expect(isNodeLike()).toBe(false)
  })

  it('falls back to root when cwd is unavailable', () => {
    setProcess({
      cwd: () => '',
      versions: { node: '22.0.0' },
    } as unknown as NodeJS.Process)
    expect(getProcessCwd()).toBe('/')

    setProcess(undefined)
    expect(getProcessCwd()).toBe('/')
  })
})

describe('cwd display helpers', () => {
  it('tildifies paths using typed process env values', () => {
    setProcess({
      env: { HOME: '/Users/simon/' },
    } as unknown as NodeJS.Process)

    expect(tildifyPath('/Users/simon/project')).toBe('~/project')
    expect(tildifyPath('/tmp/project')).toBe('/tmp/project')
  })

  it('keeps raw cwd strings outside node-like runtimes', () => {
    setProcess(undefined)
    expect(formatCwdDisplay('./apps/cli')).toBe('./apps/cli')
  })
})
