import http from 'node:http'

const host = '127.0.0.1'
const port = Number(process.env.TCS_MOCK_PORT || 18080)
const tasks = new Map()

const sendJson = (response, payload, statusCode = 200) => {
  response.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' })
  response.end(JSON.stringify(payload))
}

const success = result => ({
  success: true,
  message: '仿真接口调用成功',
  code: 200,
  result,
  timestamp: Date.now()
})

const readBody = request => new Promise((resolve, reject) => {
  let body = ''
  request.setEncoding('utf8')
  request.on('data', chunk => { body += chunk })
  request.on('end', () => {
    if (!body) {
      resolve({})
      return
    }
    try {
      resolve(JSON.parse(body))
    } catch (error) {
      reject(error)
    }
  })
  request.on('error', reject)
})

const server = http.createServer(async (request, response) => {
  const url = new URL(request.url, `http://${host}:${port}`)
  try {
    if (request.method === 'POST' && url.pathname === '/api/createExternalBusinessTask') {
      const body = await readBody(request)
      tasks.set(body.externalCode, body)
      console.log('CREATE', JSON.stringify(body))
      sendJson(response, success({ externalCode: body.externalCode }))
      return
    }

    if (request.method === 'GET' && url.pathname === '/api/getExternalBusinessTaskStatus') {
      const externalCode = url.searchParams.get('externalCode') || ''
      sendJson(response, success([{
        externalCode,
        status: '1',
        ip: '10.146.79.9',
        type: tasks.get(externalCode)?.type || 'nav_action_program',
        beginTime: '2026-07-13 14:40:00',
        endTime: '',
        remark: '仿真状态同步'
      }]))
      return
    }

    if (request.method === 'GET' && url.pathname === '/api/getMcrInfo') {
      sendJson(response, success([{
        name: 'AGV-01',
        ip: '10.146.79.9',
        speed: 0,
        power: 80,
        autoCharging: '1',
        chargingThreshold: 20,
        status: '0',
        currentPos: 'S000214',
        control: '1',
        CameraInfo: ''
      }]))
      return
    }

    const successfulGetRoutes = new Set([
      '/api/cancelExternalBusinessTask',
      '/api/stopExternalBusinessTask',
      '/api/reset',
      '/api/stopNow'
    ])
    if (request.method === 'GET' && successfulGetRoutes.has(url.pathname)) {
      console.log('GET', url.pathname, url.search)
      sendJson(response, success('成功'))
      return
    }

    sendJson(response, {
      success: false,
      message: `未实现的仿真路由：${request.method} ${url.pathname}`,
      code: 500,
      result: null,
      timestamp: Date.now()
    }, 404)
  } catch (error) {
    sendJson(response, {
      success: false,
      message: error.message,
      code: 500,
      result: null,
      timestamp: Date.now()
    }, 500)
  }
})

server.listen(port, host, () => {
  console.log(`TCS AGV mock listening on http://${host}:${port}`)
})

const close = () => server.close(() => process.exit(0))
process.on('SIGINT', close)
process.on('SIGTERM', close)
