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'

test('flowchart generation uses active AgentRun without requiring Qoder BYOK', async (t) => {
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aipros-flowchart-agentrun-'))
  process.env.DB_PATH = path.join(tempRoot, 'test.db')
  process.env.OUTPUTS_DIR = path.join(tempRoot, 'outputs')

  const originalFetch = globalThis.fetch
  globalThis.fetch = async () => new Response([
    'data: {"choices":[{"delta":{"content":"{\\"title\\":\\"请假流程\\",\\"summary\\":\\"员工请假审批\\",\\"nodes\\":[{\\"id\\":\\"start\\",\\"label\\":\\"提交申请\\",\\"actor\\":\\"员工\\"},{\\"id\\":\\"approve\\",\\"label\\":\\"审批\\",\\"actor\\":\\"主管\\"},{\\"id\\":\\"record\\",\\"label\\":\\"登记\\",\\"actor\\":\\"人事\\"},{\\"id\\":\\"end\\",\\"label\\":\\"结束\\",\\"actor\\":\\"系统\\"}],\\"edges\\":[{\\"source\\":\\"start\\",\\"target\\":\\"approve\\"},{\\"source\\":\\"approve\\",\\"target\\":\\"record\\"},{\\"source\\":\\"record\\",\\"target\\":\\"end\\"}]}"},"finish_reason":"stop"}]}',
    '',
    'data: [DONE]',
    '',
  ].join('\n'), { status: 200, headers: { 'Content-Type': 'text/event-stream' } })

  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/flowchart', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Email': '494161546@qq.com',
    },
    body: JSON.stringify({ prompt: '员工提交请假申请，主管审批后人事登记。' }),
  })

  assert.equal(res.status, 200)
  const body = await res.json()
  assert.equal(body.ok, true)
  assert.equal(body.engine.kind, 'agentrun')
  assert.equal(body.data.title, '请假流程')
  assert.equal(body.data.nodes.length, 4)
})
