// Copyright (c) 2025-2026 Withpica Ltd. All rights reserved.

/**
 * Build script: reads font files + ext-apps browser bridge,
 * writes src/apps/generated/shared-bundle.ts with const string exports.
 * Run via: npm run prebuild (before tsc)
 */

import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { createRequire } from "module";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const root = join(__dirname, "..");

// Read fonts as base64
const fontsDir = join(root, "assets/fonts");
const instrumentSerifRegular = readFileSync(
  join(fontsDir, "InstrumentSerif-Regular.woff2"),
).toString("base64");
const instrumentSerifItalic = readFileSync(
  join(fontsDir, "InstrumentSerif-Italic.woff2"),
).toString("base64");
const geistSansLight = readFileSync(
  join(fontsDir, "GeistSans-Light.woff2"),
).toString("base64");

// Read ext-apps browser bridge bundle (devDependency — may not be installed in CI)
const require = createRequire(import.meta.url);
let appBridgeJs: string;
try {
  const appBridgePath =
    require.resolve("@modelcontextprotocol/ext-apps/app-with-deps");
  appBridgeJs = readFileSync(appBridgePath, "utf-8");
} catch {
  console.warn(
    "[bundle-apps] @modelcontextprotocol/ext-apps not installed — writing stub (MCP Apps will not render)",
  );
  appBridgeJs = "/* ext-apps bridge not available */";
}

// Write generated file
const outDir = join(root, "src/apps/generated");
mkdirSync(outDir, { recursive: true });

const output = `// Auto-generated by scripts/bundle-apps.ts — do not edit
// Re-run: npm run prebuild

export const INSTRUMENT_SERIF_REGULAR_BASE64 = "${instrumentSerifRegular}";
export const INSTRUMENT_SERIF_ITALIC_BASE64 = "${instrumentSerifItalic}";
export const GEIST_SANS_LIGHT_BASE64 = "${geistSansLight}";
export const APP_BRIDGE_JS = ${JSON.stringify(appBridgeJs)};
`;

writeFileSync(join(outDir, "shared-bundle.ts"), output, "utf-8");

console.log(
  `[bundle-apps] Generated shared-bundle.ts (${Math.round(output.length / 1024)}KB)`,
);
