const express = require('express')
const path = require('path')
const net = require('net')

const appHttp = express()
const START_PORT = 9527
const MAX_PORT = 9999

// 检查端口是否可用
function isPortAvailable(port) {
  return new Promise((resolve) => {
    const server = net.createServer()
    server.listen(port, '127.0.0.1', () => {
      server.once('close', () => resolve(true))
      server.close()
    })
    server.on('error', () => resolve(false))
  })
}

// 寻找可用端口
async function findAvailablePort(startPort, maxPort) {
  for (let port = startPort; port <= maxPort; port++) {
    const available = await isPortAvailable(port)
    if (available) {
      return port
    }
  }
  throw new Error(`No available port found between ${startPort} and ${maxPort}`)
}

// 获取 dist 目录路径
let distPath
if (process.env.NODE_ENV === 'development') {
  // 开发环境
  distPath = path.join(__dirname, '..', 'dist')
} else {
  // 生产环境（打包后）
  distPath = path.join(__dirname, 'dist')
}

console.log('Serving static files from:', distPath)

// 提供静态文件
appHttp.use(express.static(distPath))

// 启动服务器
async function startServer() {
  try {
    const PORT = await findAvailablePort(START_PORT, MAX_PORT)

    const server = appHttp.listen(PORT, '127.0.0.1', () => {
      console.log(`✅ Local server running at http://127.0.0.1:${PORT}`)
    })

    // 导出服务器实例和端口，以便在需要时关闭
    return { server, PORT }
  } catch (error) {
    console.error('❌ Failed to start server:', error.message)
    throw error
  }
}

// 导出启动函数
module.exports = { startServer }
