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

const { appendFileSyncMock } = vi.hoisted(() => ({
  appendFileSyncMock: vi.fn(),
}))

vi.mock('node:fs', () => ({
  appendFileSync: appendFileSyncMock,
}))

const {
  getPerfSpanOverlapSummary,
  getPerfSpanSnapshot,
  getPerfSpanStats,
  isOneShotEnabled,
  isPerfEnabled,
  popPerfSpan,
  pushPerfSpan,
} = await import('../src/dimsdk/core/observability/perf-log.ts')

const realProcess = globalThis.process

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

function resetPerfGlobals(): void {
  delete (globalThis as typeof globalThis & {
    __DIMCODE_PERF_SPAN__?: unknown
    __DIMCODE_PERF_SPAN_HISTORY__?: unknown
  }).__DIMCODE_PERF_SPAN__
  delete (globalThis as typeof globalThis & {
    __DIMCODE_PERF_SPAN__?: unknown
    __DIMCODE_PERF_SPAN_HISTORY__?: unknown
  }).__DIMCODE_PERF_SPAN_HISTORY__
}

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

describe('perf log helpers', () => {
  it('detects one-shot and perf flags from typed process env', () => {
    setProcessEnv({
      DIMCODE_PROFILE_1SHOT: '1',
    })

    expect(isPerfEnabled()).toBe(true)
    expect(isOneShotEnabled()).toBe(true)
  })

  it('tracks active spans and overlap summaries', () => {
    setProcessEnv({})

    pushPerfSpan('render', 'frame')

    const snapshot = getPerfSpanSnapshot()
    expect(snapshot?.path).toBe('render(frame)')
    expect(snapshot?.depth).toBe(1)
    expect(getPerfSpanStats().activeDepth).toBe(1)

    const activeSummary = getPerfSpanOverlapSummary(0, Date.now() + 10)
    expect(activeSummary).toContain('render(frame):')

    popPerfSpan('render')

    expect(getPerfSpanStats()).toEqual({
      activeDepth: 0,
      historySize: 1,
    })
  })
})
