import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'

const NATIVE_WRAPPER_DLL = 'libNativeWrapper.dll'
export const WINDOWS_LAUNCHER_EXE = 'FarmControl.exe'
const LEGACY_LAUNCHER_EXE = 'launcher.exe'

export function resolveWindowsBinDir() {
  const candidates = [
    dirname(process.execPath),
    process.cwd(),
    join(dirname(process.execPath), 'bin'),
    join(process.cwd(), 'bin')
  ]

  for (const candidate of candidates) {
    if (
      existsSync(join(candidate, WINDOWS_LAUNCHER_EXE)) ||
      existsSync(join(candidate, LEGACY_LAUNCHER_EXE)) ||
      existsSync(join(candidate, NATIVE_WRAPPER_DLL))
    ) {
      return candidate
    }
  }

  return dirname(process.execPath)
}

export function ensureWindowsWorkingDirectory() {
  if (process.platform !== 'win32') {
    return
  }

  const binDir = resolveWindowsBinDir()
  const wrapperInCwd = existsSync(join(process.cwd(), NATIVE_WRAPPER_DLL))
  const wrapperInBinDir = existsSync(join(binDir, NATIVE_WRAPPER_DLL))

  if (!wrapperInCwd && wrapperInBinDir) {
    try {
      process.chdir(binDir)
    } catch {
      // Ignore if we cannot change directory.
    }
  }
}
