import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import {
  buildDeeplinkPayload,
  findProtocolUrl,
  forwardDeeplinkToRunningInstance,
  writeDeeplinkSignal
} from '../desktop/deeplink-ipc.js'

const url = findProtocolUrl(process.argv)

console.log('[deeplink] argv:', process.argv)
console.log('[deeplink] url:', url ?? null)

if (!url) {
  process.exit(1)
}

const payload = buildDeeplinkPayload(url, process.argv)
const forwarded = await forwardDeeplinkToRunningInstance(payload)

if (forwarded) {
  console.log('[deeplink] forwarded to running Farm Control instance')
  process.exit(0)
}

console.log('[deeplink] no running instance found, launching Farm Control')

writeDeeplinkSignal(payload)

const binDir = dirname(process.execPath)
const launcherPath = ['FarmControl.exe', 'launcher.exe']
  .map((name) => join(binDir, name))
  .find((candidate) => existsSync(candidate))

if (!launcherPath) {
  console.error('[deeplink] FarmControl.exe not found in', binDir)
  process.exit(1)
}

const child = spawn(launcherPath, [], {
  cwd: dirname(launcherPath),
  detached: true,
  stdio: 'ignore',
  windowsHide: true
})

child.unref()
process.exit(0)
