import assert from 'node:assert/strict'
import test from 'node:test'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
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(lines) {
  return new Response(lines.join('\r\n'), {
    status: 200,
    headers: { 'Content-Type': 'text/event-stream' },
  })
}

test('AgentRun stream handles CRLF SSE and multiple tool calls without indexes', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-agentrun-tools-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')

  let calls = 0
  const bodies = []
  const originalFetch = globalThis.fetch
  globalThis.fetch = async (_url, options = {}) => {
    calls += 1
    try { bodies.push(JSON.parse(options.body || '{}')) } catch {}
    if (calls === 1) {
      return sse([
        'data: {"choices":[{"delta":{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"list_files","arguments":"{}"}},{"id":"call_2","type":"function","function":{"name":"get_time","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}',
        '',
        'data: [DONE]',
        '',
      ])
    }
    return sse([
      'data: {"choices":[{"delta":{"content":"工具调用完成"},"finish_reason":"stop"}]}',
      '',
      'data: [DONE]',
      '',
    ])
  }

  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')
  rawDB.exec(fs.readFileSync(path.join(workerRoot, 'migrations/0010_runtime_engines.sql'), 'utf8'))
  rawDB.exec(fs.readFileSync(path.join(workerRoot, 'migrations/0011_runtime_engine_api_key.sql'), 'utf8'))
  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({ messages: [{ role: 'user', content: '请列出文件并获取时间' }] }),
  })

  assert.equal(res.status, 200)
  const text = await res.text()
  assert.match(text, /"name":"list_files"/)
  assert.match(text, /"name":"get_time"/)
  assert.match(text, /工具调用完成/)
  assert.equal(bodies[0]?.tool_choice, 'auto')
  assert.equal(calls, 2)
})
