import fs from "node:fs";
import path from "node:path";
import { html } from "common-tags";
import { normalizePath } from "vite";
import { getLogger } from "./util/logger.js";
const TEMPLATE_ENTRY_POINTS = {
    "app-fullstack": "client/root.tsx",
    "shadcn-demo-app": "root.tsx",
};
const DEFAULT_ENTRY_POINT = "root.tsx";
function getTemplateNameFromDisk(projectRoot) {
    try {
        const templatePath = path.join(projectRoot, ".sb_template");
        const value = fs.readFileSync(templatePath, "utf-8").trim();
        return value || null;
    }
    catch {
        return null;
    }
}
function getBuildEntryPoint(projectRoot) {
    const configuredEntryPoint = process.env.SUPERBLOCKS_APP_ENTRY_POINT;
    if (configuredEntryPoint) {
        return configuredEntryPoint;
    }
    const templateName = process.env.SUPERBLOCKS_APP_TEMPLATE_NAME ??
        getTemplateNameFromDisk(projectRoot);
    if (templateName && TEMPLATE_ENTRY_POINTS[templateName]) {
        return TEMPLATE_ENTRY_POINTS[templateName];
    }
    return DEFAULT_ENTRY_POINT;
}
function getIndexHtml(assetsCdnUrl, entryPoint) {
    return html `
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Code Mode</title>
        <link
          rel="icon"
          type="image/x-icon"
          href="${assetsCdnUrl}/favicon.ico"
        />
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link
          href="https://fonts.googleapis.com/css2?family=Geist+Mono:wght@100..900&family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
          rel="stylesheet"
        />
        <script>
          window._SB_VIEW_MODE = "deployed";
        </script>
        <script src="./${entryPoint}" type="module"></script>
      </head>
      <body>
        <div id="root"></div>
      </body>
    </html>
  `;
}
export const injectIndexVitePlugin = (pluginParams) => {
    const assetsCdnUrl = pluginParams.assetsCdnUrl ?? "https://prod-cdn.superblocks.com";
    return {
        name: "sb-inject-index-html",
        apply: "build",
        enforce: "pre",
        configResolved(config) {
            const indexPath = normalizePath(path.join(config.root, "index.html"));
            const logger = getLogger();
            const entryPoint = getBuildEntryPoint(config.root);
            const indexExists = fs.existsSync(indexPath);
            if (!indexExists) {
                logger.info("Injecting index.html");
                fs.writeFileSync(indexPath, getIndexHtml(assetsCdnUrl, entryPoint));
            }
        },
    };
};
//# sourceMappingURL=inject-index-vite-plugin.js.map