#!/usr/bin/env node

import {spawn} from 'node:child_process'
import process from 'node:process'

import {
  buildSmokeEnv,
  normalizeSmokeInstruction,
  startFakeDeepSeekServer,
} from './fake_deepseek_server.mjs'

const SUPER_RPA_SMOKE_SCRIPT =
  '/home/zyl/projects/superRpa/src/chrome/browser/superrpa/sgclaw/sgclaw_chat_smoke.mjs'

async function main() {
  const server = await startFakeDeepSeekServer()
  console.log(`Started fake DeepSeek server at ${server.baseUrl}`)

  try {
    await runSmoke(server.baseUrl)
    assertCompatRuntimeTraffic(server.requests)
    console.log(`Verified DeepSeek compat runtime via ${server.requests.length} provider requests.`)
  } finally {
    await server.close()
    console.log('Stopped fake DeepSeek server.')
  }
}

function runSmoke(baseUrl) {
  return new Promise((resolve, reject) => {
    const child = spawn('node', [SUPER_RPA_SMOKE_SCRIPT], {
      stdio: 'inherit',
      env: buildSmokeEnv(baseUrl),
    })

    child.once('error', reject)
    child.once('exit', (code, signal) => {
      if (code === 0) {
        resolve()
        return
      }

      if (signal) {
        reject(new Error(`browser smoke exited via signal: ${signal}`))
        return
      }

      reject(new Error(`browser smoke exited with code: ${code}`))
    })
  })
}

function assertCompatRuntimeTraffic(requests) {
  if (requests.length < 4) {
    throw new Error(`expected at least 4 provider requests, got ${requests.length}`)
  }

  const instructions = requests
    .flatMap((entry) => entry.body?.messages ?? [])
    .filter((message) => message?.role === 'user')
    .map((message) => normalizeSmokeInstruction(message.content))

  if (!instructions.includes('打开百度搜索天气')) {
    throw new Error('fake DeepSeek server did not receive the Baidu smoke instruction')
  }

  if (!instructions.includes('打开知乎搜索天气')) {
    throw new Error('fake DeepSeek server did not receive the Zhihu smoke instruction')
  }
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : String(error))
  process.exitCode = 1
})
