import { existsSync, renameSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

export const WINDOWS_LAUNCHER_EXE = 'FarmControl.exe'
const SOURCE_LAUNCHER_EXE = 'launcher.exe'

export function patchWindowsBinaries(appDir) {
  const binDir = path.join(appDir, 'bin')
  if (!existsSync(binDir)) {
    throw new Error(`patch-windows-binaries: bin directory not found at ${binDir}`)
  }

  const sourcePath = path.join(binDir, SOURCE_LAUNCHER_EXE)
  const destPath = path.join(binDir, WINDOWS_LAUNCHER_EXE)

  if (existsSync(destPath) && !existsSync(sourcePath)) {
    console.log(`patch-windows-binaries: ${WINDOWS_LAUNCHER_EXE} already present`)
    return
  }

  if (!existsSync(sourcePath)) {
    console.warn(`patch-windows-binaries: skipping missing ${sourcePath}`)
    return
  }

  if (existsSync(destPath)) {
    renameSync(destPath, `${destPath}.old`)
  }

  renameSync(sourcePath, destPath)
  console.log(
    `patch-windows-binaries: renamed ${SOURCE_LAUNCHER_EXE} -> ${WINDOWS_LAUNCHER_EXE}`
  )
}

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

  patchWindowsBinaries(path.resolve(appDirArg))
}
