import { existsSync, mkdirSync } from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'

const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const entrypoint = path.join(rootDir, 'src/bun/deeplink.js')

export function stageWindowsDeeplink(appDir) {
  if (!existsSync(entrypoint)) {
    throw new Error(`stage-windows-deeplink: entrypoint not found: ${entrypoint}`)
  }

  const outputPath = path.join(appDir, 'bin', 'deeplink.js')
  mkdirSync(path.dirname(outputPath), { recursive: true })

  const result = spawnSync(
    'bun',
    [
      'build',
      '--minify',
      '--target=bun',
      entrypoint,
      '--outfile',
      outputPath
    ],
    {
      cwd: rootDir,
      stdio: 'inherit',
      env: process.env
    }
  )

  if (result.status !== 0) {
    throw new Error(
      `stage-windows-deeplink: bun build failed with exit code ${result.status ?? 1}`
    )
  }

  if (!existsSync(outputPath)) {
    throw new Error(`stage-windows-deeplink: output not created: ${outputPath}`)
  }

  console.log(`stage-windows-deeplink: created ${outputPath}`)
  return outputPath
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const appDirArg = process.argv[2]
  if (!appDirArg) {
    console.error('Usage: bun scripts/build-windows-deeplink.mjs <app-dir>')
    process.exit(1)
  }

  stageWindowsDeeplink(path.resolve(appDirArg))
}
