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('skill-run uses configured creator and evaluator system skills for AgentRun', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-system-skill-run-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')

  const capturedSystemPrompts = []
  const originalFetch = globalThis.fetch
  globalThis.fetch = async (_url, options = {}) => {
    const payload = JSON.parse(String(options.body || '{}'))
    const systemMessage = payload.messages?.find(m => m.role === 'system')
    capturedSystemPrompts.push(systemMessage?.content || '')
    return sse('真实 AgentRun 响应')
  }

  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')

  await app.request('/api/system-skills/creator', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Email': '494161546@qq.com',
    },
    body: JSON.stringify({
      content: '# creator from configurable system skill\nUNIQUE_CREATOR_SYSTEM_SKILL',
      enabled: true,
    }),
  })
  await app.request('/api/system-skills/evaluator', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Email': '494161546@qq.com',
    },
    body: JSON.stringify({
      content: '# evaluator from configurable system skill\nUNIQUE_EVALUATOR_SYSTEM_SKILL',
      enabled: true,
    }),
  })

  const createRes = await app.request('/api/skill-run/stream', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Email': '494161546@qq.com',
    },
    body: JSON.stringify({
      mode: 'create',
      messages: [{ role: 'user', content: '生成一个合同审核 Skill' }],
    }),
  })
  assert.equal(createRes.status, 200)
  await createRes.text()

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

  assert.ok(
    capturedSystemPrompts.some(prompt => prompt.includes('UNIQUE_CREATOR_SYSTEM_SKILL')),
    'create mode should send configured creator skill content as AgentRun system prompt'
  )
  assert.ok(
    capturedSystemPrompts.some(prompt => prompt.includes('UNIQUE_EVALUATOR_SYSTEM_SKILL')),
    'evaluate mode should send configured evaluator skill content as AgentRun system prompt'
  )
  assert.ok(
    capturedSystemPrompts.some(prompt => prompt.includes('UNIQUE_EVALUATOR_SYSTEM_SKILL') && prompt.includes('必须先调用 list_files') && prompt.includes('必须调用 read_file')),
    'evaluate mode should append the real package-inspection runtime contract'
  )
})
