import { createApp } from "./createApp";
import { setupVite } from "./vite";
import { findAvailablePort } from "./port";

/**
 * DEVELOPMENT ENTRY POINT (run via `tsx watch`, never bundled by esbuild).
 * Uses Vite's dev server middleware for HMR.
 */
async function startServer() {
  const { app, server, coreRouter } = createApp();

  app.use("/", coreRouter);
  await setupVite(app, server);

  const preferredPort = parseInt(process.env.PORT || "3000");
  const port = await findAvailablePort(preferredPort);

  if (port !== preferredPort) {
    console.log(`Port ${preferredPort} is busy, using port ${port} instead`);
  }

  server.listen(port, () => {
    console.log(`Server running on http://localhost:${port}/`);
  });
}

startServer().catch(console.error);
