/* Open in Val Town: https://www.val.town/v/maxm/compileAndUploadTinygoWasm */
import * as wasmStrip from "npm:@webassemblyjs/wasm-strip";
const strip = wasmStrip.default.default;

await (async () => {
  const command = "tinygo";
  const args = [
    "build",
    "-o",
    "main.wasm",
    "-target=wasi",
    ".",
  ];
  console.log("Running", [command, ...args].join(" "));
  const cmd = new Deno.Command(command, {
    args,
    stdout: "inherit",
    stderr: "inherit",
  });

  const { code } = await cmd.output();

  console.assert(code === 0);
  console.log("Compliation complete");
})();

await (async () => {
  const command = "wasm-strip";
  const args = [
    "main.wasm",
  ];
  console.log("Running", [command, ...args].join(" "));
  const cmd = new Deno.Command(command, {
    args,
    stdout: "inherit",
    stderr: "inherit",
  });
  try {
    const { code } = await cmd.output();
    console.assert(code === 0);
  } catch (e) {
    console.log(e);
    console.log("wasm-strip failed, install with `brew install wabt`?");
    console.log("Continuing to upload without stripping");
  }
})();

let resp = await fetch("https://maxm-wasmBlobHost.web.val.run", {
  method: "POST",
  headers: {
    "Content-Type": "application/wasm",
  },
  body: Deno.readFileSync("main.wasm"),
});
console.assert(resp.status === 200);

const { url } = await resp.json();

console.log(`
Copy the following into a val town HTTP val:

import { wasmHandler } from "https://esm.town/v/maxm/tinygoHttp";
const resp = await fetch("${url}");
const handler = await wasmHandler(new Uint8Array(await resp.arrayBuffer()));
export default async function(req: Request): Promise<Response> {
  return handler(req);
}`);