import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  if (!id || id.includes("..") || id.includes("/")) {
    return new NextResponse("Invalid design system ID", { status: 400 });
  }

  const systemPath = path.join(
    process.cwd(),
    "lib",
    "scaffold",
    "open-design",
    "design-systems",
    id
  );

  const htmlPath = path.join(systemPath, "components.html");

  try {
    if (!fs.existsSync(systemPath)) {
      return new NextResponse(`Design system not found for ${id}`, { status: 404 });
    }

    if (!fs.existsSync(htmlPath)) {
      // If there's no components.html, serve a beautiful fallback UI
      // that explains this system only has Markdown guidelines for the AI
      const fallbackHtml = `
      <!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>${id} — No preview available</title>
          <style>
            body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #fbfaf9; color: #52525b; text-align: center; }
            .card { background: white; padding: 40px; border-radius: 12px; border: 1px solid #e4e4e7; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.05); max-width: 400px; }
            h2 { color: #18181b; margin-top: 0; }
            p { line-height: 1.5; font-size: 14px; }
            .badge { display: inline-block; background: #e0e7ff; color: #4338ca; padding: 4px 8px; border-radius: 6px; font-size: 12px; font-weight: 500; font-family: monospace; margin-top: 16px; }
          </style>
        </head>
        <body>
          <div class="card">
            <h2>Preview Not Available</h2>
            <p>The <strong>${id}</strong> design system is a "Rules-Only" system.</p>
            <p>It provides strict typographic, spacing, and layout instructions to the AI via its <code>DESIGN.md</code>, but it doesn't currently ship with a visual HTML preview gallery.</p>
            <div class="badge">AI Guidelines Active</div>
          </div>
        </body>
      </html>
      `;
      return new NextResponse(fallbackHtml, {
        status: 200,
        headers: {
          "Content-Type": "text/html; charset=utf-8",
          "X-Frame-Options": "SAMEORIGIN",
        },
      });
    }

    const html = await fs.promises.readFile(htmlPath, "utf-8");

    return new NextResponse(html, {
      status: 200,
      headers: {
        "Content-Type": "text/html; charset=utf-8",
        "X-Frame-Options": "SAMEORIGIN",
      },
    });
  } catch (err: any) {
    return new NextResponse(`Error loading preview: ${err.message}`, {
      status: 500,
    });
  }
}
