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, '../..')
const agentRunUrl = 'https://1242739972938523.agentrun-data.cn-hangzhou.aliyuncs.com/agent-runtimes/AIPRO-SP/endpoints/Default/invocations/openai/v1/chat/completions'

function sse(content = 'ok') {
  return new Response([
    `data: {"choices":[{"delta":{"content":"${content}"},"finish_reason":"stop"}]}`,
    '',
    'data: [DONE]',
    '',
  ].join('\n'), {
    status: 200,
    headers: { 'Content-Type': 'text/event-stream' },
  })
}

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('evaluate mode emits real package inspection tool events before model scoring', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-eval-preflight-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')
  process.env.UPLOADS_DIR = path.join(tempRoot, 'uploads')

  const packageKey = 'pkg/2026-06-28/SKILL.md'
  const packagePath = path.join(process.env.UPLOADS_DIR, packageKey)
  fs.mkdirSync(path.dirname(packagePath), { recursive: true })
  fs.writeFileSync(packagePath, '# Real Eval Test\n\n真实 Skill 包内容。\n', 'utf8')

  const originalFetch = globalThis.fetch
  globalThis.fetch = async () => sse('评测完成')

  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/0010_runtime_engines.sql')
  execMigrationOnce(rawDB, 'migrations/0011_runtime_engine_api_key.sql')
  rawDB.prepare(`
    UPDATE runtime_engines
    SET enabled = 1,
        is_active = 1,
        endpoint_public_url = ?,
        api_key = ?
    WHERE code = 'agentrun'
  `).run(agentRunUrl, 'ak-secret')

  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: 'evaluate',
      packageKey,
      messages: [{ role: 'user', content: '评测这个真实包' }],
    }),
  })
  assert.equal(res.status, 200)
  const text = await res.text()

  assert.match(text, /"t":"tool_call","name":"list_files"/)
  assert.match(text, /"t":"tool_result","name":"list_files"/)
  assert.match(text, /"t":"tool_call","name":"read_file"/)
  assert.match(text, /"t":"tool_result","name":"read_file"/)
  assert.match(text, /Real Eval Test/)
})
