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();
});

// app.use((req, res, next) => {
//    console.log('👉 请求进来了:', req.url);
//   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',//测试环境
  target: 'http://121.229.107.155:19021',//生产环境
  // target: 'http://127.0.0.1:19021',//生产环境
  changeOrigin: true,
  // pathRewrite: { '^/api1': '/api' }, //进来的path没有api了，要么直接用app.use((req, res, next)=>{})
  pathRewrite: function (path, req) {
    // console.log('31800是否走了代理', path);
    //由于app.use('/api')的原因，进入到这里后path是被去掉了api，所以要重新加上，
    return '/api' + path;
  },
  logLevel: 'silent',
  // 调试代理请求
  onProxyReq: function (proxyReq, req, res) {
    // 手动设置正确的路径（如果必要）
    // const originalPath = req.originalUrl;
    // if (originalPath.startsWith('/api1')) {
    //   const newPath = originalPath.replace('/api1', '/api');
    //   console.log('手动重写路径:', originalPath, '->', newPath);
    //   proxyReq.path = newPath;
    // }
  },
  onProxyRes: function (proxyRes, req, res) {
    // 确保 CORS 头存在
    const origin = req.headers.origin;

    // 设置响应头
    if (origin && ['http://localhost:3010', 'http://127.0.0.1:3010'].includes(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    } else {
      res.setHeader('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 ? "打包模式" : "开发模式"}`);
});
