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 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
  }
}

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

test('create mode returns plain runtime output without forcing spec files or tool calls', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-direct-create-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')

  const originalFetch = globalThis.fetch
  const bodies = []
  globalThis.fetch = async (_url, options = {}) => {
    try { bodies.push(JSON.parse(options.body || '{}')) } catch {}
    return sseFromText('这是配置智能体直接完成任务后返回的 Skill 内容。')
  }

  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: 'create',
      messages: [{ role: 'user', content: '创建客户投诉分级 Skill' }],
    }),
  })

  assert.equal(res.status, 200)
  const body = await res.text()
  assert.match(body, /配置智能体直接完成任务/)
  assert.match(body, /"state":"completed"/)
  assert.doesNotMatch(body, /"t":"error"/)
  assert.doesNotMatch(body, /skill\.spec\.json|SKILL\.md|examples\.md|rubric\.md/)
  assert.equal(bodies[0]?.tool_choice, 'auto')
  assert.notDeepEqual(bodies[0]?.tool_choice, {
    type: 'function',
    function: { name: 'write_file' },
  })
})
