import { build } from "esbuild"
import { readdir } from "node:fs/promises"
import { dirname, resolve } from "node:path"
import { fileURLToPath } from "node:url"

const bridgeRoot = dirname(fileURLToPath(import.meta.url))
const webPanelRoot = resolve(bridgeRoot, "..")
const distRoot = resolve(webPanelRoot, "dist")
const bridgeEntryPoint = resolve(bridgeRoot, "src", "index.ts")
const bridgeOutfile = resolve(distRoot, "bridge.cjs")
const rendererScriptsRoot = resolve(bridgeRoot, "scripts", "default")
const rendererScriptsOutdir = resolve(distRoot, "renderer-scripts")

await build({
    banner: {
        js: "// Generated by bridge/build.mjs. Do not edit this bundle by hand.",
    },
    bundle: true,
    entryPoints: [bridgeEntryPoint],
    format: "cjs",
    legalComments: "none",
    minify: true,
    outfile: bridgeOutfile,
    platform: "node",
    target: "node16",
})

const EXCLUDED_RENDERER_SCRIPTS = new Set(["activate-pro.js"])

const rendererEntries = (
    await readdir(rendererScriptsRoot, { withFileTypes: true })
)
    .filter(
        (entry) =>
            entry.isFile() &&
            entry.name.endsWith(".js") &&
            !EXCLUDED_RENDERER_SCRIPTS.has(entry.name)
    )
    .map((entry) => resolve(rendererScriptsRoot, entry.name))

if (rendererEntries.length === 0) {
    throw new Error(`No renderer script entries found in ${rendererScriptsRoot}`)
}

await build({
    banner: {
        js: "// Generated by bridge/build.mjs. Do not edit this bundle by hand.",
    },
    bundle: true,
    entryNames: "[name]",
    entryPoints: rendererEntries,
    format: "iife",
    legalComments: "none",
    minify: true,
    outdir: rendererScriptsOutdir,
    platform: "browser",
    target: "es2020",
})

console.log(`Built ${bridgeOutfile}`)
console.log(
    `Built ${rendererEntries.length} renderer script(s) in ${rendererScriptsOutdir}`
)
