#!/usr/bin/env node

const fs = require('node:fs')
const path = require('node:path')
const { spawnSync } = require('node:child_process')

function defaultElectronExecutable() {
  switch (process.platform) {
    case 'darwin':
      return 'Electron.app/Contents/MacOS/Electron'
    case 'win32':
      return 'electron.exe'
    default:
      return 'electron'
  }
}

function electronRoot() {
  return path.dirname(require.resolve('electron/package.json'))
}

function ensureElectron() {
  const root = electronRoot()
  const pathFile = path.join(root, 'path.txt')
  const relativeExecutable = fs.existsSync(pathFile)
    ? fs.readFileSync(pathFile, 'utf8').trim()
    : defaultElectronExecutable()
  const executable = path.join(root, 'dist', relativeExecutable)

  if (fs.existsSync(executable)) {
    if (!fs.existsSync(pathFile)) fs.writeFileSync(pathFile, relativeExecutable)
    return executable
  }

  console.log('Installing Electron runtime for HyperDesk...')
  const result = spawnSync(process.execPath, [path.join(root, 'install.js')], {
    stdio: 'inherit',
    env: process.env,
  })

  if (result.status !== 0) {
    throw new Error(`Electron install script failed with exit code ${result.status}`)
  }

  const installedRelativeExecutable = fs.existsSync(pathFile)
    ? fs.readFileSync(pathFile, 'utf8').trim()
    : defaultElectronExecutable()
  const installedExecutable = path.join(root, 'dist', installedRelativeExecutable)

  if (!fs.existsSync(installedExecutable)) {
    throw new Error(
      `Electron install completed but executable was not found. Expected: ${installedExecutable}\n` +
      'This usually means Electron binary download/extraction was blocked. Try: npm install -g hyperdesk --foreground-scripts'
    )
  }

  return installedExecutable
}

try {
  ensureElectron()
} catch (error) {
  console.error(error?.stack || error?.message || String(error))
  process.exit(1)
}
