// Starts the Vite dev or preview server, tolerating the CLI flags the platform
// appends to `npm run dev` / `npm run start` (notably the legacy Next.js
// `--hostname`, which the Vite CLI rejects). Usage: node scripts/serve.mjs <dev|preview>
import { createServer, preview } from 'vite';

const [mode = 'dev', ...rest] = process.argv.slice(2);

const server = {};
for (let i = 0; i < rest.length; i++) {
  const arg = rest[i];
  if (arg === '--host' || arg === '--hostname') {
    const next = rest[i + 1];
    if (next && !next.startsWith('--')) {
      server.host = next;
      i++;
    } else {
      server.host = true;
    }
  } else if (arg === '--port') {
    server.port = Number(rest[++i]);
  }
}

if (server.port === undefined && process.env.FRONT_PORT) {
  server.port = Number(process.env.FRONT_PORT);
}

if (mode === 'preview') {
  const s = await preview({ preview: server });
  s.printUrls();
} else {
  const s = await createServer({ server });
  await s.listen();
  s.printUrls();
}
