/**
 * VERA Extension Build Script
 * 
 * Bundles the BBS+ WASM library + background.js into a single file
 * that works as a Chrome MV3 service worker.
 * 
 * Usage: node build.js
 */

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const LIB_DIR = join(__dirname, "node_modules/@mattrglobal/bbs-signatures/lib");

console.log("📦 Building VERA Vault service worker...");

// Read all the library source files
const wasmBs64 = readFileSync(join(LIB_DIR, "wasm_bs64.js"), "utf-8");
const wasmJs = readFileSync(join(LIB_DIR, "wasm.js"), "utf-8");
const wasmModule = readFileSync(join(LIB_DIR, "wasm_module.js"), "utf-8");

// Read the source background.js
const backgroundSrc = readFileSync(join(__dirname, "src/background.js"), "utf-8");

// Strip import statements from background.js (we use bundled globals instead)
const backgroundClean = backgroundSrc.replace(/^import\s+.*$/gm, "// (import removed — using bundled globals)");

// Build the parts
const parts = [];

parts.push("// ═══════════════════════════════════════════════════════════════");
parts.push("// VERA Vault — Bundled Service Worker");
parts.push("// Auto-generated by build.js — DO NOT EDIT DIRECTLY");
parts.push("// Contains: @mattrglobal/bbs-signatures (WASM) + background logic");
parts.push("// ═══════════════════════════════════════════════════════════════");
parts.push("");

// Buffer polyfill
parts.push("// ─── Polyfills for Service Worker environment ──────────────────");
parts.push(`
const Buffer = {
  from: function(data, encoding) {
    if (encoding === 'base64') {
      const binary = atob(data);
      const bytes = new Uint8Array(binary.length);
      for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
      return bytes;
    }
    if (typeof data === 'string') {
      return new TextEncoder().encode(data);
    }
    return new Uint8Array(data);
  }
};
`);

// Stablelib random polyfill
parts.push("// ─── @stablelib/random polyfill ──────────────────────────────");
parts.push(`
const stablelibRandom = {
  randomBytes: function(n) {
    const bytes = new Uint8Array(n);
    crypto.getRandomValues(bytes);
    return bytes;
  }
};
`);

// wasm_bs64.js
parts.push("// ─── Step 1: wasm_bs64.js (base64-encoded WASM binary) ──────");
parts.push("const __wasm_bs64_module = { exports: {} };");
parts.push("(function(module, exports) {");
parts.push(wasmBs64);
parts.push("})(__wasm_bs64_module, __wasm_bs64_module.exports);");
parts.push("");

// wasm.js
parts.push("// ─── Step 2: wasm.js (wasm-bindgen glue code) ────────────────");
parts.push("const __wasm_js_module = { exports: {} };");
parts.push("(function(module, exports, require) {");
parts.push(wasmJs);
parts.push("})(__wasm_js_module, __wasm_js_module.exports, function(name) {");
parts.push("  if (name === './wasm_bs64.js') return __wasm_bs64_module.exports;");
parts.push("  throw new Error('Unknown require: ' + name);");
parts.push("});");
parts.push("");

// wasm_module.js
parts.push("// ─── Step 3: wasm_module.js (high-level BBS+ API) ──────────");
parts.push("const __bbs_module = { exports: {} };");
parts.push("(function(module, exports, require) {");
parts.push(wasmModule);
parts.push("})(__bbs_module, __bbs_module.exports, function(name) {");
parts.push("  if (name === './wasm.js') return __wasm_js_module.exports;");
parts.push("  if (name === '@stablelib/random') return stablelibRandom;");
parts.push("  throw new Error('Unknown require: ' + name);");
parts.push("});");
parts.push("");

// Extract the BBS+ functions
parts.push("// ─── BBS+ API (extracted from module) ────────────────────────");
parts.push("const blsCreateProof = __bbs_module.exports.blsCreateProof;");
parts.push("const blsVerifyProof = __bbs_module.exports.blsVerifyProof;");
parts.push("const blsSign = __bbs_module.exports.blsSign;");
parts.push("const blsVerify = __bbs_module.exports.blsVerify;");
parts.push("const generateBls12381G2KeyPair = __bbs_module.exports.generateBls12381G2KeyPair;");
parts.push("");

// The actual VERA background logic
parts.push("// ─── VERA Vault Logic ──────────────────────────────────────");
parts.push(backgroundClean);

// Join everything
const bundle = parts.join("\n");

// Write output
const distDir = join(__dirname, "dist");
if (!existsSync(distDir)) mkdirSync(distDir);
writeFileSync(join(distDir, "background.js"), bundle);

const sizeKB = Math.round(bundle.length / 1024);
console.log("✅ Built dist/background.js (" + sizeKB + " KB)");
console.log("   Contains: BBS+ WASM (base64) + service worker logic");
console.log("   Ready to load in Chrome → chrome://extensions/");
