import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
  buildUserToolsFromStore,
  hydrateToolsStateFromConfig,
  loadMcpJson,
} from '../src/dimsdk/compat/archships/dim-agent/config/tools-store.ts'

const tempHomes: string[] = []

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

describe('tools store helpers', () => {
  it('loads legacy object-form mcp.json into the server array', async () => {
    const home = mkdtempSync(`${tmpdir()}/best-agent-tools-store-`)
    tempHomes.push(home)
    const env = { HOME: home }
    mkdirSync(join(home, '.dimcode'), { recursive: true })
    writeFileSync(
      join(home, '.dimcode', 'mcp.json'),
      JSON.stringify({
        mcpServers: {
          calendar: {
            id: 'calendar',
            transport: 'stdio',
            command: 'python3',
            args: ['/tmp/calendar.py'],
          },
        },
      }),
      'utf8',
    )

    const loaded = await loadMcpJson(env)

    expect(loaded.servers).toEqual([
      {
        id: 'calendar',
        name: 'calendar',
        transport: 'stdio',
        command: 'python3',
        args: ['/tmp/calendar.py'],
      },
    ])
  })

  it('builds and hydrates tools state without relying on any-shaped store access', () => {
    const built = buildUserToolsFromStore({
      prev: { version: 1, updatedAt: 0 },
      store: {
        state: {
          tools: {
            websearch: {
              apiKey: 'serper-key',
              apiEndpoint: 'https://example.test/search',
              numResults: 5,
            },
          },
          mcp: {
            servers: [
              {
                id: 'calendar',
                name: 'Calendar',
                transport: 'stdio',
                command: 'python3',
                args: ['calendar.py'],
              },
            ],
          },
        },
      },
    })

    const state = {
      tools: {
        websearch: {
          apiKey: '',
          apiEndpoint: '',
          numResults: 0,
        },
      },
      mcp: {
        servers: [],
      },
    }

    hydrateToolsStateFromConfig(built, state)

    expect(state.tools.websearch).toEqual({
      apiKey: 'serper-key',
      apiEndpoint: 'https://example.test/search',
      numResults: 5,
    })
    expect(state.mcp.servers).toEqual([
      {
        id: 'calendar',
        name: 'Calendar',
        transport: 'stdio',
        command: 'python3',
        args: ['calendar.py'],
      },
    ])
  })
})
