import type { APIRoute } from "astro";
import { readFileSync, existsSync } from "fs";
import { join } from "path";

// Serve the studio SPA for all /studio/* paths (including /studio itself).
// Static assets under /studio/assets/* are served before this route fires.
export const GET: APIRoute = () => {
  const indexPath = join(process.cwd(), "dist/studio-index.html");

  if (!existsSync(indexPath)) {
    return new Response(
      "<p>Sanity Studio has not been built. Check the Docker build logs.</p>",
      { status: 503, headers: { "Content-Type": "text/html" } }
    );
  }

  // Rewrite absolute asset paths from /static/ to /studio/static/ so
  // the studio's JS/CSS/icons load correctly when hosted at /studio.
  const html = readFileSync(indexPath, "utf-8")
    .replaceAll('="/static/', '="/studio/static/')
    .replaceAll("='/static/", "='/studio/static/");

  return new Response(html, {
    status: 200,
    headers: { "Content-Type": "text/html; charset=utf-8" },
  });
};
