import { execFile } from 'node:child_process'
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { promisify } from 'node:util'
import { installVerifiedTarball } from '@contrast/runtime-delivery'
import { windowAdmission } from './admitted-mac-build'
import binaryenLock from './binaryen.lock.json' with { type: 'json' }
import { rnxHomeDir } from './home-paths'
import {
  dropBoundaryExports,
  NARROW_MERGE_NAMES,
  narrowWasmBoundary,
} from './wasm-narrow-boundary'

// the linked wasm64 executable, made loadable: its host boundary narrowed to
// 32 bits and its memory and table lowered to 32-bit addresses, so pointers stay
// 8 bytes in memory while every browser runs the module. clang's own optimizer
// pass is off (-O0 on the link) so the artifact never depends on the machine;
// the pinned Binaryen size-optimizes once per cached artifact instead. the
// features are the ones the link declares.
const FEATURES = [
  'memory64',
  'threads',
  'bulk-memory',
  'bulk-memory-opt',
  'call-indirect-overlong',
  'exception-handling',
  'multivalue',
  'mutable-globals',
  'nontrapping-float-to-int',
  'reference-types',
  'sign-ext',
]

// PEACH_SWIFT_NAMES=1 keeps the name section so a trap stack names its functions.
export const KEEP_WASM_NAMES = process.env.PEACH_SWIFT_NAMES === '1'

const LOWERING = ['--memory64-lowering', '--table64-lowering']
const BINARYEN_VERSION = binaryenLock.version
const runBinaryen = promisify(execFile)

/** feeds the artifact hash: a new optimizer or flag set is a new artifact. */
export const WASM_LOWER_IDENTITY = `binaryen ${BINARYEN_VERSION} narrow ${LOWERING.join(' ')} ${FEATURES.join(',')} unoptimized-names`

const BINARYEN_RELEASES = new Map(Object.entries(binaryenLock.platforms))

// skipPasses names Binaryen passes to leave out. a guest link with several images
// skips duplicate-function-elimination, which would merge identical functions
// that different images must keep separate.
async function runWasmOpt(
  file: string,
  output: string,
  optimize: boolean,
  skipPasses: readonly string[],
  binary: string,
): Promise<void> {
  const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES)
  const requestedCores = Number(process.env.BINARYEN_CORES)
  const environment: NodeJS.ProcessEnv = { ...process.env }
  if (Number.isInteger(admittedCores) && admittedCores > 0)
    environment.BINARYEN_CORES = String(
      Number.isInteger(requestedCores) && requestedCores > 0
        ? Math.min(admittedCores, requestedCores)
        : admittedCores,
    )
  const features = FEATURES.map((feature) => `--enable-${feature}`)
  // an unoptimized link keeps its name section, as before lowering, so a trap names its function
  const names = optimize && !KEEP_WASM_NAMES ? [] : ['-g']
  const narrowed = narrowWasmBoundary(readFileSync(file))
  const merged = `${output}.narrowed`
  if (narrowed) {
    const guest = `${output}.guest`
    const thunks = `${output}.thunks.wat`
    writeFileSync(guest, narrowed.module)
    writeFileSync(thunks, narrowed.thunks)
    await runBinaryen(
      join(dirname(binary), 'wasm-merge'),
      [
        ...features,
        ...names,
        guest,
        NARROW_MERGE_NAMES.guest,
        thunks,
        NARROW_MERGE_NAMES.boundary,
        '-o',
        merged,
      ],
      { env: environment },
    )
    writeFileSync(merged, dropBoundaryExports(readFileSync(merged)))
    rmSync(guest)
    rmSync(thunks)
  }
  try {
    await runBinaryen(
      binary,
      [
        ...LOWERING,
        ...(optimize ? ['-Oz'] : []),
        ...names,
        ...skipPasses.flatMap((pass) => ['--skip-pass', pass]),
        ...features,
        narrowed ? merged : file,
        '-o',
        output,
      ],
      { env: environment, maxBuffer: Infinity },
    )
  } finally {
    if (narrowed) rmSync(merged)
  }
}

// use the same verified binary on every host so the artifact identity is true.
async function installWasmOpt(): Promise<string> {
  const platform = `${process.platform}-${process.arch}`
  const release = BINARYEN_RELEASES.get(platform)
  if (!release) throw new Error(`no pinned Binaryen release for ${platform}`)
  const destDir = join(rnxHomeDir(), 'tools', 'binaryen', BINARYEN_VERSION, platform)
  const binary = join(destDir, 'bin', 'wasm-opt')
  if (!existsSync(binary))
    await installVerifiedTarball({
      url: `https://r2.rnxsim.com/peach/binaryen/${release.sha256}/${platform}.tar.gz`,
      digest: { algorithm: 'sha256', encoding: 'hex', value: release.sha256 },
      destDir,
      installedMarker: 'bin/wasm-opt',
      label: `Binaryen ${BINARYEN_VERSION}`,
    })
  return binary
}

export async function lowerWasm(
  file: string,
  output: string,
  options: { optimize: boolean; skipPasses?: readonly string[] },
): Promise<void> {
  await runWasmOpt(
    file,
    output,
    options.optimize,
    options.skipPasses ?? [],
    await installWasmOpt(),
  )
}
