import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const workerRoot = path.resolve(__dirname, '../..')

function execMigrationOnce(db, file) {
  try {
    db.exec(fs.readFileSync(path.join(workerRoot, file), 'utf8'))
  } catch (error) {
    if (!/duplicate column|already exists/i.test(error?.message || '')) throw error
  }
}

test('skill-run stream requires a registered runtime instead of falling back to legacy Qoder runtime', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-agentrun-required-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')

  const originalFetch = globalThis.fetch
  let fetchCalled = false
  globalThis.fetch = async () => {
    fetchCalled = true
    return new Response('unexpected runtime call', { status: 500 })
  }

  t.after(() => {
    globalThis.fetch = originalFetch
    fs.rmSync(tempRoot, { recursive: true, force: true })
  })

  const { default: app } = await import('../index.js')
  const { rawDB } = await import('../db.js')
  execMigrationOnce(rawDB, 'migrations/0005_llm_providers.sql')
  execMigrationOnce(rawDB, 'migrations/0006_qoder_provider.sql')
  execMigrationOnce(rawDB, 'migrations/0010_runtime_engines.sql')
  execMigrationOnce(rawDB, 'migrations/0011_runtime_engine_api_key.sql')
  rawDB.prepare(`
    UPDATE llm_providers
    SET enabled = 1,
        is_active = 1,
        api_key = ?
    WHERE code = 'qoder'
  `).run('pt-legacy-qoder-token')
  rawDB.prepare(`
    UPDATE runtime_engines
    SET enabled = 0,
        is_active = 0,
        endpoint_public_url = NULL,
        api_key = NULL
    WHERE code = 'agentrun'
  `).run()

  const res = await app.request('/api/skill-run/stream', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Email': '494161546@qq.com',
    },
    body: JSON.stringify({
      mode: 'run',
      systemPrompt: '# runner',
      messages: [{ role: 'user', content: '运行一下' }],
    }),
  })

  assert.equal(res.status, 503)
  const body = await res.json()
  assert.match(body.error, /运行时/)
  assert.equal(fetchCalled, false)
})
