import express from "express";
import { createServer as createViteServer } from "vite";
import path from "path";

async function startServer() {
  const app = express();
  const PORT = 3000;

  app.use(express.json());

  // In-memory data store for the backend
  const dataStore = {
    projects: [
      { id: 1, name: 'Autonomous_Nav_Cam_Left.mp4', frames: 1240, status: 'Ready', fps: 30, thumbnail: 'bg-zinc-800' },
      { id: 2, name: 'Store_Checkout_Aisle_1.mkv', frames: 450, status: 'Processing', fps: 15, thumbnail: 'bg-zinc-800' },
      { id: 3, name: 'Medical_Scans_Series_A', frames: 80, status: 'Ready', fps: '图像序列', thumbnail: 'bg-zinc-800' },
      { id: 4, name: 'Drone_Survey_Forest.mp4', frames: 3200, status: 'Ready', fps: 60, thumbnail: 'bg-zinc-800' },
    ],
    templates: [
      { id: 1, name: 'Cityscapes_v2_Mapping', classes: 34, rules: 8 },
      { id: 2, name: 'Medical_Cell_Segment', classes: 4, rules: 2 },
      { id: 3, name: 'COCO_Panoptic_Base', classes: 133, rules: 12 },
    ]
  };

  // Auth endpoint
  app.post("/api/login", (req, res) => {
    const { username, password } = req.body;
    if (username === "admin" && password === "123456") {
      res.json({ token: "fake-jwt-token-for-admin" });
    } else {
      res.status(401).json({ error: "Invalid credentials" });
    }
  });

  // Data endpoints
  app.get("/api/projects", (req, res) => {
    res.json(dataStore.projects);
  });

  app.get("/api/templates", (req, res) => {
    res.json(dataStore.templates);
  });

  // Vite middleware for development
  if (process.env.NODE_ENV !== "production") {
    const vite = await createViteServer({
      server: { middlewareMode: true },
      appType: "spa",
    });
    app.use(vite.middlewares);
  } else {
    const distPath = path.join(process.cwd(), 'dist');
    app.use(express.static(distPath));
    app.get('*', (req, res) => {
      res.sendFile(path.join(distPath, 'index.html'));
    });
  }

  app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server running on http://localhost:${PORT}`);
  });
}

startServer();
