// peach's binding of the shared runtime-delivery machinery for the native
// desktop host. the host releases on its own (packages/peach-desktop's Native
// Desktop Release workflow) and explicit installs download and verify each version
// into ~/.peach/desktop/versions/<version>/, exactly as `peach runtime install` manages
// the engine runtime. on macOS the active version is at /Applications/Peach.app,
// where Spotlight finds it and the CLI, the fleet installer and the app's own
// updater share it. each channel publishes its own manifest per platform, so
// the staging and production queues never write the same object. linux stores
// its active version under ~/.peach and bundles node and software vulkan.

import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { createRuntimeDelivery, type RuntimeDelivery } from '@contrast/runtime-delivery'
import { cacheDir, desktopHostDir, desktopHostsDir, ensureRnxHome } from './home-paths.ts'

export const DESKTOP_HOST_CDN_ORIGIN = 'https://r2.rnxsim.com'
export const DESKTOP_HOST_CHANNELS = ['production', 'staging'] as const
export type DesktopHostChannel = (typeof DESKTOP_HOST_CHANNELS)[number]
const CHANNEL_ENV = 'PEACH_DESKTOP_CHANNEL'

// the mac host targets macOS 26 (packages/peach-desktop/native/Info.plist
// LSMinimumSystemVersion): an older mac cannot launch it, so it gets no host
// and opens the simulator in the browser window, as a mac without one does.
const MAC_HOST_MINIMUM_MAJOR = 26
let macMeetsHostMinimum: boolean | undefined

/** the artifact platform this machine installs, or null where no host ships. */
export function desktopHostPlatform(): 'mac-arm64' | 'linux-x64' | null {
  if (process.platform === 'darwin' && process.arch === 'arm64') {
    macMeetsHostMinimum ??=
      Number(
        /<key>ProductVersion<\/key>\s*<string>(\d+)/.exec(
          fs.readFileSync('/System/Library/CoreServices/SystemVersion.plist', 'utf8'),
        )?.[1],
      ) >= MAC_HOST_MINIMUM_MAJOR
    return macMeetsHostMinimum ? 'mac-arm64' : null
  }
  if (process.platform === 'linux' && process.arch === 'x64') return 'linux-x64'
  return null
}

/** the executable inside an installed version, relative to its directory. */
export function desktopHostExecutable(): string {
  return desktopHostPlatform() === 'linux-x64'
    ? 'bin/node'
    : 'PeachDesktop.app/Contents/MacOS/PeachDesktop'
}

export const MAC_HOST_APP = '/Applications/Peach.app'
const HOST_BUNDLE_ID = 'dev.contrast.peach-desktop'

// the host's identity: the manifest checksum proves the bytes are the published
// ones, this proves who signed them
const HOST_REQUIREMENT =
  '=anchor apple generic and identifier "dev.contrast.peach-desktop" and certificate leaf[subject.OU] = "399WY8X9HY" and certificate leaf[field.1.2.840.113635.100.6.1.13] exists'

function verifyHost(dir: string): void {
  const app = path.join(dir, 'PeachDesktop.app')
  // runner-toolchain-platform: darwin
  const signature = spawnSync('codesign', [
    '--verify',
    '--deep',
    '--strict',
    '-R',
    HOST_REQUIREMENT,
    app,
  ])
  // runner-toolchain-platform: darwin
  const notarization = spawnSync('spctl', ['--assess', '--type', 'execute', app])
  if (signature.status !== 0 || notarization.status !== 0) {
    throw new Error(`${app} failed Developer ID or notarization verification`)
  }
}

function bundleValue(app: string, key: string): string | null {
  // runner-toolchain-platform: darwin
  const read = spawnSync(
    'plutil',
    ['-extract', key, 'raw', '-o', '-', path.join(app, 'Contents/Info.plist')],
    { encoding: 'utf8' },
  )
  return read.status === 0 ? read.stdout.trim() : null
}

/** whether `app` is the native host, as opposed to the Electron app, which
 *  installs to the same path on a case-insensitive disk. */
export function isNativeHostBundle(app: string): boolean {
  return (
    process.platform === 'darwin' &&
    bundleValue(app, 'CFBundleIdentifier') === HOST_BUNDLE_ID
  )
}

/** a default production install owns the scheme until uninstall or home purge. */
export function registerNativeDesktopLinks(): void {
  if (
    desktopHostPlatform() !== 'mac-arm64' ||
    !isNativeHostBundle(MAC_HOST_APP) ||
    bundleValue(MAC_HOST_APP, 'PeachUpdateChannel') !== 'production'
  )
    return
  const receipt = path.join(desktopHostsDir(), 'url-handler.json')
  fs.mkdirSync(desktopHostsDir(), { recursive: true })
  const script = `
ObjC.import('CoreServices');
ObjC.import('Foundation');
ObjC.bindFunction('LSCopyDefaultHandlerForURLScheme', ['id', ['id']]);
ObjC.bindFunction('LSSetDefaultHandlerForURLScheme', ['int', ['id', 'id']]);
ObjC.bindFunction('LSCopyAllHandlersForURLScheme', ['id', ['id']]);
const current = ObjC.unwrap($.LSCopyDefaultHandlerForURLScheme('peach')) || null;
const handlers = ObjC.deepUnwrap($.LSCopyAllHandlersForURLScheme('peach')) || [];
const previous = current === ${JSON.stringify(HOST_BUNDLE_ID)}
  ? handlers.find(handler => handler !== ${JSON.stringify(HOST_BUNDLE_ID)}) || null : current;
if (current !== ${JSON.stringify(HOST_BUNDLE_ID)} || ${!fs.existsSync(receipt)}) {
  const data = $.NSString.stringWithString(JSON.stringify({ previous })).dataUsingEncoding($.NSUTF8StringEncoding);
  if (!data.writeToFileAtomically(${JSON.stringify(receipt)}, true))
    throw new Error('native URL handler receipt write failed');
}
const registered = $.LSRegisterURL($.NSURL.fileURLWithPath(${JSON.stringify(MAC_HOST_APP)}), true);
if (registered !== 0) throw new Error('native URL registration failed: ' + registered);
const selected = $.LSSetDefaultHandlerForURLScheme('peach', ${JSON.stringify(HOST_BUNDLE_ID)});
if (selected !== 0) throw new Error('native URL handler selection failed: ' + selected);
if (ObjC.unwrap($.LSCopyDefaultHandlerForURLScheme('peach')) !== ${JSON.stringify(HOST_BUNDLE_ID)})
  throw new Error('native URL handler readback failed');
`
  // runner-toolchain-platform: darwin
  const result = spawnSync('/usr/bin/osascript', ['-l', 'JavaScript', '-e', script], {
    encoding: 'utf8',
  })
  if (result.status !== 0)
    throw new Error(`native deep-link registration failed: ${result.stderr.trim()}`)
}

/** restore the captured handler only while this install still owns the scheme. */
export function unregisterNativeDesktopLinks(): void {
  if (desktopHostPlatform() !== 'mac-arm64') return
  const receipt = path.join(desktopHostsDir(), 'url-handler.json')
  if (!fs.existsSync(receipt)) return
  const state: unknown = JSON.parse(fs.readFileSync(receipt, 'utf8'))
  if (
    typeof state !== 'object' ||
    state === null ||
    !('previous' in state) ||
    (state.previous !== null && typeof state.previous !== 'string')
  )
    throw new Error('invalid native URL registration receipt')
  const script = `
ObjC.import('CoreServices');
ObjC.bindFunction('LSCopyDefaultHandlerForURLScheme', ['id', ['id']]);
ObjC.bindFunction('LSSetDefaultHandlerForURLScheme', ['int', ['id', 'id']]);
const current = ObjC.unwrap($.LSCopyDefaultHandlerForURLScheme('peach'));
const previous = ${JSON.stringify(state.previous)};
if (current === ${JSON.stringify(HOST_BUNDLE_ID)} && previous) {
  const status = $.LSSetDefaultHandlerForURLScheme('peach', previous);
  if (status !== 0 || ObjC.unwrap($.LSCopyDefaultHandlerForURLScheme('peach')) !== previous)
    throw new Error('native URL handler restore failed: ' + status);
}
`
  // runner-toolchain-platform: darwin
  run('/usr/bin/osascript', ['-l', 'JavaScript', '-e', script])
  // runner-toolchain-platform: darwin
  run(
    '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister',
    ['-u', MAC_HOST_APP],
  )
  fs.unlinkSync(receipt)
}

export function uninstallNativeDesktopHost(): void {
  unregisterNativeDesktopLinks()
  if (desktopHostPlatform() === 'mac-arm64' && isNativeHostBundle(MAC_HOST_APP))
    fs.rmSync(MAC_HOST_APP, { recursive: true, force: true })
  fs.rmSync(desktopHostsDir(), { recursive: true, force: true })
}

function placedHostVersion(): string | null {
  if (desktopHostPlatform() === 'linux-x64') {
    try {
      const version = fs
        .readFileSync(path.join(desktopHostsDir(), 'active'), 'utf8')
        .trim()
      return /^\d+\.\d+$/.test(version) &&
        fs.existsSync(path.join(desktopHostDir(version), desktopHostExecutable()))
        ? version
        : null
    } catch {
      return null
    }
  }
  return isNativeHostBundle(MAC_HOST_APP)
    ? bundleValue(MAC_HOST_APP, 'CFBundleVersion')
    : null
}

/** the active native host's app bundle, or null when none is installed. */
export function activeDesktopHostApp(): string | null {
  return process.platform === 'darwin' && placedHostVersion() ? MAC_HOST_APP : null
}

/** protocol 4 binds port zero before publishing the host origin and evaluates
 *  in its realms over node ipc for the process that started it, answering each
 *  realm as it settles, with persistent browser context storage. the receipt
 *  travels inside the checksummed archive and signed mac bundle. bind its
 *  declaration to the entry bytes so a receipt cannot bless another source. */
export function hostEntrySupportsAutomaticPort(hostEntry: string): boolean {
  try {
    const contract: unknown = JSON.parse(
      fs.readFileSync(
        path.join(path.dirname(hostEntry), 'headless-contract.json'),
        'utf8',
      ),
    )
    return (
      typeof contract === 'object' &&
      contract !== null &&
      'protocol' in contract &&
      contract.protocol === 4 &&
      'entrySha256' in contract &&
      contract.entrySha256 ===
        createHash('sha256').update(fs.readFileSync(hostEntry)).digest('hex')
    )
  } catch {
    return false
  }
}

/** the installed standalone host command; the driver appends its connection arguments. */
export function headlessHostCommand(): string[] | null {
  const platform = desktopHostPlatform()
  if (!platform) return null
  if (platform === 'mac-arm64') {
    const app = process.env.PEACH_DESKTOP_APP
      ? path.resolve(process.env.PEACH_DESKTOP_APP)
      : activeDesktopHostApp()
    if (!app) return null
    const launcher = path.join(app, 'Contents/Frameworks/node')
    const host = path.join(app, 'Contents/Resources/node/host.mjs')
    // releases before the bundled launcher have no headless host, and releases
    // before the automatic-port bind cannot serve `--port 0`; use the browser
    if (!fs.existsSync(launcher) || !hostEntrySupportsAutomaticPort(host)) return null
    return [launcher, '--experimental-vm-modules', host]
  }
  const pin = desktopHostDelivery().resolvePin()
  if (pin && !/^\d+\.\d+$/.test(pin))
    throw new Error(`invalid native host version '${pin}' (expected <build>.<attempt>)`)
  const version = pin || placedHostVersion()
  if (!version) return null
  const dir = desktopHostDir(version)
  if (!fs.existsSync(path.join(dir, desktopHostExecutable()))) return null
  // a placed host that predates the automatic-port bind upgrades like a missing one
  if (!hostEntrySupportsAutomaticPort(path.join(dir, 'node/host.mjs'))) return null
  return [
    path.join(dir, 'bin/node'),
    '--experimental-vm-modules',
    path.join(dir, 'node/host.mjs'),
  ]
}

function run(command: string, args: string[]): void {
  const result = spawnSync(command, args, { encoding: 'utf8' })
  if (result.status !== 0)
    throw new Error(`${command} ${args.join(' ')} failed: ${result.stderr.trim()}`)
}

// lands a verified cached version at /Applications/Peach.app. the copy is an
// APFS clone of the cache, so it costs no space, and it swaps in by rename so a
// failure leaves the previous app in place. an Electron app in the slot moves to
// ~/Applications, where the CLI still finds it.
function placeHost(version: string): void {
  if (desktopHostPlatform() === 'linux-x64') {
    const active = path.join(desktopHostsDir(), 'active')
    const incoming = `${active}.${process.pid}.tmp`
    fs.writeFileSync(incoming, `${version}\n`)
    fs.renameSync(incoming, active)
    return
  }
  if (placedHostVersion() === version) return
  const parent = path.dirname(MAC_HOST_APP)
  const incoming = path.join(parent, `.Peach-incoming-${process.pid}.app`)
  const previous = path.join(parent, `.Peach-previous-${process.pid}.app`)
  try {
    // a clone that fails partway (a full disk) leaves no hidden bundle behind in /Applications
    run('cp', ['-cR', path.join(desktopHostDir(version), 'PeachDesktop.app'), incoming])
    if (fs.existsSync(MAC_HOST_APP)) {
      if (isNativeHostBundle(MAC_HOST_APP)) fs.renameSync(MAC_HOST_APP, previous)
      else {
        const electron = path.join(os.homedir(), 'Applications/peach.app')
        if (fs.existsSync(electron))
          throw new Error(
            `${MAC_HOST_APP} holds another app and ${electron} exists; move one aside`,
          )
        fs.mkdirSync(path.dirname(electron), { recursive: true })
        fs.renameSync(MAC_HOST_APP, electron)
      }
    }
    fs.renameSync(incoming, MAC_HOST_APP)
  } catch (err) {
    if (fs.existsSync(previous) && !fs.existsSync(MAC_HOST_APP))
      fs.renameSync(previous, MAC_HOST_APP)
    throw err
  } finally {
    fs.rmSync(incoming, { recursive: true, force: true })
    fs.rmSync(previous, { recursive: true, force: true })
  }
}

function isChannel(value: string): value is DesktopHostChannel {
  return DESKTOP_HOST_CHANNELS.some((channel) => channel === value)
}

export function desktopHostDelivery(channelInput?: string): RuntimeDelivery {
  const platform = desktopHostPlatform()
  if (!platform) {
    throw new Error(
      `the native desktop host ships for Apple silicon on macOS ${MAC_HOST_MINIMUM_MAJOR} or later and Linux x64 (this is ${process.platform}-${process.arch}); open the simulator with --driver playwright --headed`,
    )
  }
  const channel = channelInput || process.env[CHANNEL_ENV] || 'production'
  if (!isChannel(channel)) {
    throw new Error(
      `unknown desktop channel '${channel}' (use ${DESKTOP_HOST_CHANNELS.join(' or ')})`,
    )
  }
  const prefix = `/releases/native/${channel}`
  return createRuntimeDelivery({
    id: 'peach desktop',
    defaultCdnOrigin: DESKTOP_HOST_CDN_ORIGIN,
    manifestPath: `${prefix}/manifest-${platform}.json`,
    tarballPath: (version) =>
      platform === 'linux-x64'
        ? `${prefix}/${version}/PeachHost-${version}-${platform}.tar.gz`
        : `${prefix}/${version}/PeachDesktop-${version}-${platform}.zip`,
    installedMarker: desktopHostExecutable(),
    verifyInstall: platform === 'mac-arm64' ? verifyHost : undefined,
    env: {
      cdnOrigin: 'PEACH_DESKTOP_CDN_ORIGIN',
      channel: CHANNEL_ENV,
      pin: 'PEACH_DESKTOP_VERSION',
    },
    defaultChannel: channel,
    ensureHome: ensureRnxHome,
    // the engine runtime owns ~/.peach/config.json's channel and pin keys
    configFile: () => path.join(desktopHostsDir(), 'config.json'),
    runtimesDir: desktopHostsDir,
    runtimeDir: desktopHostDir,
    cacheDir,
    readActiveRuntime: placedHostVersion,
    writeActiveRuntime: placeHost,
  })
}
