import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { afterEach, describe, expect, it } from 'vitest'
import {
  ACTIVE_SESSION_ENV_KEYS,
  flushActiveSessionWritesForTests,
  publishActiveSession,
  readActiveSessionRecordForTests,
  teardownActiveSession,
  updateActiveSessionVisibility,
} from '../src/dimsdk/cli/active-session.ts'

const tempHomes: string[] = []

afterEach(async () => {
  for (const key of ACTIVE_SESSION_ENV_KEYS.sessionId)
    delete process.env[key]
  for (const key of ACTIVE_SESSION_ENV_KEYS.folder)
    delete process.env[key]
  await flushActiveSessionWritesForTests()
  while (tempHomes.length > 0) {
    rmSync(tempHomes.pop() as string, { force: true, recursive: true })
  }
})

describe('active session runtime record', () => {
  it('publishes focused records and clears exported env on blur', async () => {
    const home = mkdtempSync(`${tmpdir()}/best-agent-active-session-`)
    tempHomes.push(home)
    const env = { HOME: home }

    publishActiveSession({
      sessionId: 'session-123',
      cwd: '/workspace/project',
      title: 'Thread title',
      env,
    })
    await flushActiveSessionWritesForTests()

    expect(readActiveSessionRecordForTests(env)).toMatchObject({
      sessionId: 'session-123',
      cwd: '/workspace/project',
      focused: true,
      visibility: 'focused',
      title: 'Thread title',
    })
    expect(process.env.DIMCODE_ACTIVE_SESSION_ID).toBe('session-123')
    expect(process.env.DIMCODE_ACTIVE_SESSION_FOLDER).toBe('/workspace/project')

    updateActiveSessionVisibility({
      visibility: 'blurred',
      env,
    })
    await flushActiveSessionWritesForTests()

    expect(readActiveSessionRecordForTests(env)).toMatchObject({
      sessionId: 'session-123',
      cwd: '/workspace/project',
      focused: false,
      visibility: 'blurred',
    })
    expect(process.env.DIMCODE_ACTIVE_SESSION_ID).toBeUndefined()
    expect(process.env.DIMCODE_ACTIVE_SESSION_FOLDER).toBeUndefined()

    teardownActiveSession({ env })
    await flushActiveSessionWritesForTests()
  })
})
