import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createDimcodeContext } from '../src/dimsdk/cli/context.ts'
import { saveDimcodeUserConfig } from '../src/dimsdk/cli/user-cache.ts'

const tempHomes: string[] = []

afterEach(() => {
  while (tempHomes.length > 0) {
    rmSync(tempHomes.pop() as string, { force: true, recursive: true })
  }
})

describe('cli context provider hydration', () => {
  it('rewrites legacy custom provider ids to the saved custom provider record', async () => {
    const home = mkdtempSync(`${tmpdir()}/best-agent-context-`)
    tempHomes.push(home)
    const env = { HOME: home }

    await saveDimcodeUserConfig(join(home, '.dimcode', 'config.json'), {
      version: 1,
      updatedAt: 1,
      settings: {
        providerId: 'custom',
        activeModelByProvider: {
          cp_gateway: 'claude-3-7-sonnet',
        },
        customProviders: [
          {
            id: 'cp_gateway',
            name: 'Gateway',
            adapter: 'anthropic',
            apiKey: 'anthropic-key',
            baseUrl: 'https://anthropic.gateway/v1',
            models: [{ id: 'claude-3-7-sonnet' }],
          },
        ],
      },
    })

    const result = await createDimcodeContext({
      cwd: process.cwd(),
      env,
    })

    expect(result.context.env).toMatchObject({
      DIMCODE_PROVIDER_ID: 'cp_gateway',
      DIMCODE_PROVIDER_NAME: 'Gateway',
      DIMCODE_PROVIDER_ADAPTER: 'anthropic',
      DIMCODE_MODEL: 'claude-3-7-sonnet',
      DIMCODE_ANTHROPIC_BASE_URL: 'https://anthropic.gateway/v1',
      ANTHROPIC_API_KEY: 'anthropic-key',
    })
    expect(result.config.settings?.providerId).toBe('cp_gateway')
  })
})
