const express = require('express');
const path = require('path');
const http = require('http');
const WebSocket = require('ws');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fs = require('fs');

const app = express();
const PORT = 3010;

// 检测是否在 pkg 打包环境中
const isPacked = typeof process.pkg !== 'undefined';

// 动态获取静态文件路径
function getStaticPath() {
  if (isPacked) {
    const possiblePaths = [
      path.join(process.cwd(), 'dist'),
      path.join(__dirname, 'dist')
    ];
    for (const staticPath of possiblePaths) {
      try {
        const testPath = path.join(staticPath, 'index.html');
        if (fs.existsSync(testPath)) {
          //console.log(`Found static files at: ${staticPath}`);
          return staticPath;
        }
      } catch (error) {
        continue;
      }
    }
    return path.join(__dirname, 'dist');
  } else {
    return path.join(__dirname, 'dist');
  }
}

const staticPath = getStaticPath();
//console.log(`Serving static files from: ${staticPath}`);

// 1. CORS 中间件 - 放在最前面
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-API-Key');
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }
  next();
});

// 2. CSP配置 - 简化版本避免冲突
app.use((req, res, next) => {
  // 对于API请求，使用更宽松的CSP或者不设置
  if (req.path.startsWith('/api')) {
    next();
  } else {
    res.setHeader('Content-Security-Policy',
      "default-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
      "connect-src 'self' http: https: ws: wss:; " +
      "img-src 'self' data: blob: http: https:;"
    );
    next();
  }
});

// 3. API代理 - 简化版本
app.use('/api', createProxyMiddleware({
  target: 'http://121.229.107.155:2251',
  changeOrigin: true,
  pathRewrite: { '^/api': '/api' },
  logLevel: 'debug',
  onProxyRes: function (proxyRes, req, res) {
    // 确保代理响应包含正确的CORS头
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
    proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';
  },
  onError: (err, req, res) => {
    console.error('Proxy Error:', err);
    res.status(500).json({ error: 'Proxy error' });
  }
}));

// 4. 静态文件服务
app.use(express.static(staticPath));

// 5. 处理根路径请求
app.get('/', (req, res) => {
  const indexPath = path.join(staticPath, 'index.html');
  if (fs.existsSync && !fs.existsSync(indexPath)) {
    console.error(`Index.html not found at: ${indexPath}`);
    return res.status(404).send('index.html not found');
  }
  res.sendFile(indexPath);
});

// 6. 处理.well-known路径 
app.get('/.well-known/appspecific/com.chrome.devtools.json', (req, res) => {
  res.json({});
});

// 7. 创建HTTP和WebSocket服务
const server = http.createServer(app);
//console.log("此时的WebSocket",server);

const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  //console.log(ws, '连接------');

  ws.send('连接成功');
  ws.on('message', (message) => {
    //console.log(message.toString(), ':ue发送给vue的数据');
    ws.send('vue发给ue的数据+1');
  });
  ws.on('close', () => {
    //console.log('客户端断开连接');
  });
  ws.on('error', (error) => {
    console.error('WebSocket错误:', error);
  });
});

server.listen(PORT, () => {
  //console.log(`大屏中转服务启动: http://localhost:${PORT}`);
  //console.log(`静态文件目录: ${staticPath}`);
  //console.log(`运行模式: ${isPacked ? '打包模式' : '开发模式'}`);
});



