import { afterEach, describe, expect, it, vi } from 'vitest'

const realProcess = globalThis.process

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

async function loadModule() {
  vi.resetModules()
  return await import('../src/dimsdk/core/tool-output-pagination.ts')
}

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

describe('tool output pagination', () => {
  it('reads page sizes from typed process env at module init', async () => {
    setProcessEnv({
      DIMCODE_TOOL_OUTPUT_MAX_LINES: '500',
      DIMCODE_TOOL_OUTPUT_INITIAL_LINES: '120',
      DIMCODE_TOOL_OUTPUT_LOAD_MORE_LINES: '80',
    })

    const mod = await loadModule()

    expect(mod.MAX_EXPANDED_TOOL_OUTPUT_LINES).toBe(500)
    expect(mod.INITIAL_EXPANDED_TOOL_OUTPUT_LINES).toBe(120)
    expect(mod.LOAD_MORE_TOOL_OUTPUT_LINES).toBe(80)
    expect(mod.clampExpandedToolOutputLines(999)).toBe(500)
  })

  it('falls back when env values are invalid', async () => {
    setProcessEnv({
      DIMCODE_TOOL_OUTPUT_MAX_LINES: '-1',
      DIMCODE_TOOL_OUTPUT_INITIAL_LINES: 'nope',
      DIMCODE_TOOL_OUTPUT_LOAD_MORE_LINES: '0',
    })

    const mod = await loadModule()

    expect(mod.MAX_EXPANDED_TOOL_OUTPUT_LINES).toBe(2000)
    expect(mod.INITIAL_EXPANDED_TOOL_OUTPUT_LINES).toBe(200)
    expect(mod.LOAD_MORE_TOOL_OUTPUT_LINES).toBe(200)
    expect(mod.clampExpandedToolOutputLines(0)).toBe(200)
  })
})
