import { ensureWindowsWorkingDirectory } from '../desktop/windows-app-paths.js'
import {
  captureLaunchUrl,
  closeSingleInstanceServer,
  ensureSingleInstanceLock
} from '../desktop/single-instance.js'

ensureWindowsWorkingDirectory()

const launchUrl = captureLaunchUrl()
const gotSingleInstanceLock = await ensureSingleInstanceLock({ launchUrl })

if (!gotSingleInstanceLock) {
  process.exit(0)
}

const { createAppRpc } = await import('../desktop/rpc.js')
const {
  registerGlobalShortcuts,
  unregisterGlobalShortcuts
} = await import('../desktop/spotlight.js')
const {
  createMainWindow,
  handleDeepLinkFromArgv,
  setupDevAuthServer,
  setupNavigationGestures,
  setupWindowsDeepLinkHandling
} = await import('../desktop/window.js')

setupWindowsDeepLinkHandling()

const rpc = createAppRpc()
const mainWindow = await createMainWindow(rpc)

setupNavigationGestures(mainWindow)
registerGlobalShortcuts(rpc)
setupDevAuthServer()
handleDeepLinkFromArgv(launchUrl)

process.on('exit', () => {
  unregisterGlobalShortcuts()
  closeSingleInstanceServer()
})
