#!/usr/bin/env node
// Mizan codegen npm-package shim — dispatches to the platform-appropriate
// `mizan-generate` Rust binary in this directory. Source for the binary
// lives at `protocol/mizan-codegen/`; published releases ship one binary
// per supported platform.

import { spawn } from 'child_process'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { existsSync } from 'fs'
import { platform, arch } from 'os'

const here = dirname(fileURLToPath(import.meta.url))

const platforms = {
    'linux-x64':   'mizan-generate-linux-x64',
    'darwin-arm64': 'mizan-generate-darwin-arm64',
    'darwin-x64':  'mizan-generate-darwin-x64',
    'win32-x64':   'mizan-generate-win32-x64.exe',
}

const key = `${platform()}-${arch()}`
const binName = platforms[key]
if (!binName) {
    console.error(`[mizan-generate] no prebuilt binary for ${key}`)
    process.exit(1)
}

const binPath = join(here, binName)
if (!existsSync(binPath)) {
    console.error(`[mizan-generate] binary missing: ${binPath}`)
    console.error('[mizan-generate] build from source: cargo build --release --manifest-path <mizan>/protocol/mizan-codegen/Cargo.toml')
    process.exit(1)
}

const child = spawn(binPath, process.argv.slice(2), { stdio: 'inherit' })
child.on('exit', code => process.exit(code ?? 1))
child.on('error', err => {
    console.error(`[mizan-generate] failed to spawn ${binPath}: ${err.message}`)
    process.exit(1)
})
