import express, { type Express } from "express";
import fs from "fs";
import path from "path";

export function serveStatic(app: Express) {
  // Robust path resolution for Unikernel environment
  const cwd = process.cwd();
  let distPath = path.resolve(__dirname, "public");

  // Fallback: If __dirname based path fails, try relative to CWD
  if (!fs.existsSync(distPath)) {
    // Assuming structure is /dist/public or just /public depending on how CWD is set
    const altPath = path.join(cwd, "dist", "public");
    if (fs.existsSync(altPath)) {
        distPath = altPath;
    } else {
        // Try just "public" if CWD is already inside dist (unlikely but possible)
        const rootPublic = path.join(cwd, "public");
        if (fs.existsSync(rootPublic)) distPath = rootPublic;
    }
  }

  if (!fs.existsSync(distPath)) {
    throw new Error(`Could not find the build directory: ${distPath}`);
  }

  app.use(express.static(distPath));

  // fall through to index.html if the file doesn't exist
  app.use("*", (req, res) => {
    res.sendFile(path.resolve(distPath, "index.html"));
  });
}

