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('run mode uses the runner contract plus loaded skill content, not creator or evaluator skills', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-run-mode-'))
  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('运行完成')
  }

  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 runRes = 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: '# Loaded Runner Skill\nUNIQUE_RUNNER_SKILL_CONTENT',
      messages: [{ role: 'user', content: '真实运行这个 Skill' }],
    }),
  })
  assert.equal(runRes.status, 200)
  await runRes.text()

  const runPrompt = capturedSystemPrompts.find(prompt => prompt.includes('UNIQUE_RUNNER_SKILL_CONTENT')) || ''
  assert.match(runPrompt, /Skill 运行契约/)
  assert.match(runPrompt, /UNIQUE_RUNNER_SKILL_CONTENT/)
  assert.doesNotMatch(runPrompt, /UNIQUE_CREATOR_SYSTEM_SKILL|UNIQUE_EVALUATOR_SYSTEM_SKILL/)
})
