import { execFileSync, spawn, spawnSync } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import {
  detachBundleGlobalFooter,
  stripBundleMetadataFooter,
} from '@peach/globals/bundle-global-footer'
import {
  insertPackageVersionsFooter,
  readPackageVersions,
  readPackageVersionsFooter,
  type PackageVersions,
} from '@peach/globals/package-versions'
import {
  extractAssetDescriptors,
  metroAssetScaleFilename,
} from '../../../contrast-bundler/src/metroAssetArtifact'
import { isSwiftIcuPacked } from '../../../sootsim-swift/src/icuData'
import {
  APP_PACKAGE_ORIGIN,
  APP_PACKAGE_ADDRESS_PATTERN,
  packageSettingDefaults,
  type AppPackageManifest,
} from '../../src/appPackageContract'
import { getCliRuntime, verifyCliCompanion } from '../../src/cli-runtime'
import { produceConfiguredBundle } from '../../src/configured-bundle-producer'
import { activeDesktopHostApp } from '../../src/desktop-host-delivery'
import { readExpoSwiftFooter } from '../../src/expoSwiftContract'
import { readActiveRuntime, rnxHomeDir } from '../../src/home-paths'
import {
  captureStagedHostFiles,
  stageHostBytes,
  stageHostLaunchMetadata,
} from '../../src/host/staged-host-files'
import { readInstalledNativePackageVersionsAsync } from '../../src/installed-package-versions'
import { isRecord } from '../../src/is-record'
import { detectBundleModeFromText } from '../../src/metro-production-bundle'
import { readNativeAppIdentityFromProject } from '../../src/native-app-identity-project'
import {
  buildNativeBundles,
  insertNativeBundleFooters,
  nativeBundleAssets,
} from '../../src/native-bundles'
import { readExpoConfigAsync } from '../../src/native-firebase-config'
import { terminateProcessGroup } from '../../src/process-group'
import { resolveActiveRuntimeRoot } from '../../src/runtime-assets'
import { discoverAppCatalog } from '../app-catalog'
import { loadRNXAppConfig } from '../app-config'
import { resolveAppProject, type ResolvedAppProject } from '../app-project'
import {
  parseAppSplashWire,
  splashImageUrls,
  splashImageContentType,
} from '../app-splash'
import { prepareNativeInput, resolveNativeInput } from '../native-input'
import { packagedAppLauncher } from '../packaged-app-launcher'
import { IS_STANDALONE } from '../standalone'
import { CliUsageError } from '../usage-error'
import {
  buildShellUrl,
  resolveAppProjectForBundleUrl,
  stagePrebuiltBundle,
} from './control'

const origin = APP_PACKAGE_ORIGIN

// a launch compiles every script the app runs as it starts. the bytecode v8 keeps from one launch
// here ships in the bundle, where the realms read it (peach-desktop node/realm.mjs), so the first
// launch on any mac skips that compile. realms write their cache as they close.
async function primeCodeCache(app: string, home: string): Promise<void> {
  const peach = path.join(app, 'Contents', 'Resources', 'bin', 'peach')
  const env = {
    ...process.env,
    PEACH_HOME: home,
    PEACH_CLI_CURRENT_SIM_PATH: path.join(home, 'current-sim.json'),
  }
  const nodeHost = path.join(home, 'desktop', 'node-host')
  fs.mkdirSync(nodeHost, { recursive: true })
  const hostLog = path.join(home, 'host.log')
  const hostOutput = fs.openSync(hostLog, 'a', 0o600)
  const host = spawn(
    path.join(app, 'Contents', 'MacOS', 'PeachApp'),
    ['--peach-app-home', home],
    { stdio: ['ignore', hostOutput, hostOutput], detached: true },
  )
  fs.closeSync(hostOutput)
  const startupFailure = (detail: string) => {
    const logs = [hostLog, path.join(home, 'runtime.log')]
      .filter((file) => fs.existsSync(file))
      .map((file) => `${path.basename(file)}:\n${fs.readFileSync(file, 'utf8')}`)
      .join('\n')
    const directory = path.join(rnxHomeDir(), 'package-diagnostics')
    fs.mkdirSync(directory, { recursive: true, mode: 0o700 })
    const diagnostic = path.join(directory, `${randomUUID()}.log`)
    fs.writeFileSync(diagnostic, `${detail}\n${logs}`, { mode: 0o600 })
    return new Error(`${detail}\n${logs.slice(-4000)}\nstartup log: ${diagnostic}`)
  }
  const exited = new Promise<NodeJS.Signals | null>((resolve) =>
    host.once('exit', (_code, signal) => resolve(signal)),
  )
  const deadline = Date.now() + 120_000
  const record = path.join(home, 'app-runtime.json')
  await new Promise<void>((resolve, reject) => {
    const watcher = fs.watch(home, () => {
      if (fs.existsSync(record)) done()
    })
    const timer = setTimeout(
      () => done(new Error('the packaged runtime did not start')),
      120_000,
    )
    function done(error?: Error) {
      watcher.close()
      clearTimeout(timer)
      if (error) reject(error)
      else resolve()
    }
    if (fs.existsSync(record)) done()
  }).catch(async (error: unknown) => {
    await terminateProcessGroup(host, 'SIGKILL')
    throw startupFailure(error instanceof Error ? error.message : String(error))
  })
  const service: { pid: number; bridgePort: number } = JSON.parse(
    fs.readFileSync(record, 'utf8'),
  )
  const bridgeEnv = { ...env, PEACH_BRIDGE_PORT: String(service.bridgePort) }
  // the cli finds no sim until the host's page reaches the app's service. a first screen may
  // animate for as long as it shows (a spinner while it connects), so the launch counts once painted
  for (;;) {
    const ready = spawnSync(
      peach,
      [
        'wait',
        'ready',
        '--painted',
        '--max-ms',
        String(Math.max(1000, deadline - Date.now())),
      ],
      { env: bridgeEnv, encoding: 'utf8' },
    )
    if (ready.status === 0) break
    if (Date.now() > deadline) {
      await terminateProcessGroup(host, 'SIGKILL')
      throw startupFailure(
        `the packaged app did not start: ${(ready.stderr + ready.stdout).slice(-400)}`,
      )
    }
    await new Promise((resolve) => setTimeout(resolve, 500))
  }
  // what the first screen runs once its data arrives belongs in the cache too
  spawnSync(peach, ['wait', 'idle', '--max-ms', '10000'], { env: bridgeEnv })
  host.kill('SIGTERM')
  const quit = setTimeout(() => void terminateProcessGroup(host, 'SIGKILL'), 30_000)
  if ((await exited) === 'SIGKILL') throw new Error('the packaged app did not quit')
  clearTimeout(quit)
  spawnSync('/bin/kill', [String(service.pid)])
  const seeded = path.join(app, 'Contents', 'Resources', 'code-cache')
  fs.mkdirSync(seeded)
  for (const entry of fs.readdirSync(nodeHost, {
    recursive: true,
    withFileTypes: true,
  }))
    // a partial write carries its thread's suffix
    if (
      entry.isFile() &&
      path.basename(entry.parentPath) === 'code-cache' &&
      !entry.name.includes('.')
    )
      fs.copyFileSync(
        path.join(entry.parentPath, entry.name),
        path.join(seeded, entry.name),
      )
  // the realms its first page started, for the host to start before webkit loads the page (node/host.mjs)
  const prestart = path.join(nodeHost, 'realm-prestart.json')
  if (fs.existsSync(prestart))
    fs.copyFileSync(
      prestart,
      path.join(app, 'Contents', 'Resources', 'realm-prestart.json'),
    )
}

async function projectIcon(
  project: string,
  scratch: string,
): Promise<string | undefined> {
  const config = await readExpoConfigAsync(project)
  if (typeof config.icon === 'string') return path.resolve(project, config.icon)
  const artwork = readNativeAppIdentityFromProject(project, 'ios')?.appIconArtwork
    ?.primary?.[0]?.uri
  if (!artwork?.startsWith('data:')) return undefined
  const icon = path.join(scratch, 'icon.png')
  fs.writeFileSync(icon, Buffer.from(artwork.slice(artwork.indexOf(',') + 1), 'base64'))
  return icon
}

export async function runPackage(args: string[]): Promise<void> {
  if (process.platform !== 'darwin')
    throw new CliUsageError('peach package currently builds macOS apps')
  const input = [...args]
  const values = new Map<string, string>()
  const settings: string[] = []
  const launchEnvironmentFiles: Record<string, string> = {}
  const positionals: string[] = []
  for (let i = 0; i < input.length; i++) {
    const flag = input[i]!
    if (!flag.startsWith('-')) {
      positionals.push(flag)
      continue
    }
    if (
      ![
        '--name',
        '--output',
        '--identifier',
        '--icon',
        '--splash',
        '--setting',
        '--launch-env-file',
        '--cli',
        '--host-app',
        '--target',
        '--scheme',
        '--activity',
        '--variant',
        '--package-versions',
        '--project-root',
        '--sign',
        '--notarize',
      ].includes(flag)
    )
      throw new CliUsageError(`unknown peach package option: ${flag}`)
    const value = input[++i]
    if (!value || value.startsWith('--'))
      throw new CliUsageError(`${flag} requires a value`)
    if (flag === '--setting') settings.push(value)
    else if (flag === '--launch-env-file') {
      // KEY=PATH: the launching host reads PATH (~/ is the user's home) at each
      // launch into the app's ProcessInfo.environment, so the value never
      // enters the package, its launch url or its logs
      const equals = value.indexOf('=')
      if (
        equals < 1 ||
        !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.slice(0, equals)) ||
        equals === value.length - 1
      )
        throw new CliUsageError(`--launch-env-file expects KEY=PATH, got ${value}`)
      launchEnvironmentFiles[value.slice(0, equals)] = value.slice(equals + 1)
    } else values.set(flag, value)
  }
  const target = positionals[0]
  if (!target || positionals.length !== 1)
    throw new CliUsageError(
      'usage: peach package <target> --name <name> [--output <app|zip|dmg> --setting key=value --launch-env-file KEY=PATH --sign <identity> --notarize <profile>]',
    )
  const name = values.get('--name') ?? path.basename(target, path.extname(target))
  const identifier =
    values.get('--identifier') ??
    `dev.peach.app.${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`
  if (
    !name.trim() ||
    /[/\0]/.test(name) ||
    !/^[A-Za-z0-9]+(?:[.-][A-Za-z0-9-]+)+$/.test(identifier)
  )
    throw new CliUsageError('package name or bundle identifier is invalid')
  const output = path.resolve(values.get('--output') ?? `${name}.app`)
  const archive = path.extname(output)
  if (!['.app', '.zip', '.dmg'].includes(archive) || fs.existsSync(output))
    throw new CliUsageError('--output must name a new .app, .zip or .dmg')
  // a Developer ID identity signs with the hardened runtime; notarization reads
  // credentials saved by `xcrun notarytool store-credentials <profile>`
  const identity = values.get('--sign')
  const notaryProfile = values.get('--notarize')
  if (identity && !identity.startsWith('Developer ID Application: '))
    throw new CliUsageError('--sign needs a Developer ID Application identity')
  if (notaryProfile && !identity) throw new CliUsageError('--notarize needs --sign')
  const defaults = packageSettingDefaults(settings)
  const versionsFile = values.get('--package-versions')
  const versions = versionsFile
    ? readPackageVersions(JSON.parse(fs.readFileSync(path.resolve(versionsFile), 'utf8')))
    : null
  let configuredVersions: PackageVersions | null = null
  const prepareBundle = async (source: string) => {
    source = source.replaceAll(origin, '')
    if (versions || configuredVersions)
      source = insertPackageVersionsFooter(source, {
        ...configuredVersions,
        ...readPackageVersionsFooter(source),
        ...versions,
      })
    const runtime = getCliRuntime()
    // the package's bytes never change, so each launch evaluates the executable
    // prepared here instead of analyzing and transforming the bundle again.
    return runtime.render_worker_prepared_boot_bundle.prepareBootBundle(
      await runtime.rolldown_bundle_inventory.attachRolldownBundleHttpPayload(
        source,
        'application/javascript',
      ),
    )
  }
  const selectedHost =
    values.get('--host-app') ?? process.env.PEACH_DESKTOP_APP ?? activeDesktopHostApp()
  const host = selectedHost ? path.resolve(selectedHost) : null
  const runtime = resolveActiveRuntimeRoot()
  const runtimeVersion = readActiveRuntime()
  if (!host || !runtime || !runtimeVersion)
    throw new CliUsageError(
      'install the Peach desktop app and an engine runtime before packaging',
    )
  verifyCliCompanion(runtime)
  const cli =
    values.get('--cli') ??
    (IS_STANDALONE
      ? process.execPath
      : path.resolve(import.meta.dirname, '../../dist-bin/peach-darwin-arm64'))
  if (!fs.existsSync(cli))
    throw new CliUsageError(
      'source packaging needs a built CLI binary; pass --cli <binary>',
    )
  // the app is assembled beside the output, so archives and the final move stay on its volume
  const staging = `${output}.${randomUUID()}`
  const temporary = path.join(staging, `${name}.app`)
  fs.mkdirSync(path.dirname(output), { recursive: true })
  fs.mkdirSync(staging)
  const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'peach-package-'))
  const routes: AppPackageManifest['routes'] = {}
  let icon = values.get('--icon')
  let iconUrl: string | undefined
  let requiresServer = false
  const route = (pathname: string, bytes: Uint8Array, contentType: string) => {
    const extension = contentType === 'application/javascript' ? '.js' : ''
    const url = stageHostBytes(bytes, origin, extension)
    routes[pathname] = { file: path.basename(new URL(url).pathname), contentType }
    return origin + pathname
  }
  // the shell picks its tenant artifact from the bundle url before fetching the
  // bundle, so the url names the bundle's mode; a production bundle behind a bare
  // url boots the development tenant first and restarts on every launch.
  const routeBundle = async (pathname: string, source: string) => {
    const bundle = new URL(route(pathname, Buffer.from(source), 'application/javascript'))
    const mode = await detectBundleModeFromText(source)
    if (mode) bundle.searchParams.set('dev', String(mode === 'development'))
    const url = new URL('/rn', origin)
    url.searchParams.set('bundle', bundle.href)
    const expoSwift = readExpoSwiftFooter(source)
    if (expoSwift)
      url.searchParams.set(
        'expoSwift',
        route(
          '/__peach/expo-swift.json',
          Buffer.from(JSON.stringify(expoSwift)),
          'application/json',
        ),
      )
    return url.href
  }
  try {
    const captured = await captureStagedHostFiles(async () => {
      const configureProjectBundle = async (
        input: string,
        project: ResolvedAppProject,
        platform: string,
      ) => {
        const root = project.appDir
        const config = await loadRNXAppConfig(project)
        let source = detachBundleGlobalFooter(input, '__peachExpoSwift').source
        source = detachBundleGlobalFooter(source, '__peachExpoKotlin').source
        source = stripBundleMetadataFooter(source, 'nitro')
        source = stripBundleMetadataFooter(source, 'oneSDK')
        source = stripBundleMetadataFooter(source, 'turbo')
        // a production bundle runs on a Release build, any other on Debug
        const natives = await buildNativeBundles(
          root,
          platform === 'android' ? 'android' : 'ios',
          (await detectBundleModeFromText(source)) === 'production' ? 'Release' : 'Debug',
        )
        for (const asset of nativeBundleAssets(natives))
          route('/' + asset.path, asset.bytes, asset.contentType)
        source = insertNativeBundleFooters(source, natives, (file) => '/' + file).source
        return produceConfiguredBundle(
          source,
          config,
          new Set(
            Object.keys({
              ...configuredVersions,
              ...readPackageVersionsFooter(source),
              ...versions,
            }),
          ),
        )
      }
      let launchUrl: string
      const native = resolveNativeInput(target)
      const local = fs.statSync(path.resolve(target), { throwIfNoEntry: false })
      const project = local
        ? resolveAppProject(
            local.isDirectory() ? target : path.dirname(path.resolve(target)),
          )
        : null
      const configuredProject = values.has('--project-root')
        ? resolveAppProject(values.get('--project-root')!)
        : project
      if (values.has('--project-root') && !configuredProject)
        throw new CliUsageError('--project-root must name an app project')
      if (configuredProject)
        configuredVersions = await readInstalledNativePackageVersionsAsync(
          configuredProject.appDir,
        )
      if (!icon && configuredProject)
        icon = await projectIcon(configuredProject.appDir, scratch)
      if (native) {
        const app = await prepareNativeInput(native, {
          origin,
          target: values.get('--target'),
          scheme: values.get('--scheme'),
          activity: values.get('--activity'),
          variant: values.get('--variant'),
        })
        try {
          for (const [pathname, asset] of app.assets)
            route(pathname, asset.bytes, asset.contentType)
          route(
            app.metadataPath,
            Buffer.from(JSON.stringify(app.metadata)),
            'application/json',
          )
          launchUrl = await routeBundle(app.guestPath, app.guestSource)
          if (!icon && app.icon) {
            icon = path.join(scratch, 'icon.png')
            fs.writeFileSync(icon, app.icon.bytes)
          }
        } finally {
          app.dispose()
        }
      } else if (
        (local?.isFile() && target.endsWith('.json')) ||
        /^https?:\/\/.+\.json(?:\?.*)?$/.test(target)
      ) {
        const readChannel = async (): Promise<unknown> => {
          if (local?.isFile())
            return JSON.parse(fs.readFileSync(path.resolve(target), 'utf8'))
          const response = await fetch(target)
          if (!response.ok)
            throw new Error(`app release metadata: HTTP ${response.status}`)
          return response.json()
        }
        const channel = await readChannel()
        if (
          !isRecord(channel) ||
          channel.schemaVersion !== 1 ||
          typeof channel.bundleUrl !== 'string' ||
          typeof channel.bundleHash !== 'string' ||
          !/^[a-f0-9]{64}$/.test(channel.bundleHash) ||
          typeof channel.iconUrl !== 'string'
        )
          throw new Error('invalid app release metadata')
        const bundleResponse = await fetch(channel.bundleUrl)
        if (!bundleResponse.ok)
          throw new Error(`app release bundle: HTTP ${bundleResponse.status}`)
        const bytes = Buffer.from(await bundleResponse.arrayBuffer())
        if (createHash('sha256').update(bytes).digest('hex') !== channel.bundleHash)
          throw new Error('app release bundle hash mismatch')
        let source = bytes.toString('utf8')
        const resources = new Set<string>()
        const icuUrls = new Set<string>()
        const visit = (value: unknown) => {
          if (Array.isArray(value)) {
            for (const child of value) visit(child)
            return
          }
          if (!isRecord(value)) return
          for (const [key, child] of Object.entries(value)) {
            if ((key === 'url' || key === 'icuUrl') && typeof child === 'string') {
              resources.add(child)
              if (key === 'icuUrl') icuUrls.add(child)
            } else visit(child)
          }
        }
        if (configuredProject) {
          source = await configureProjectBundle(
            source,
            configuredProject,
            channel.platform === 'android' ? 'android' : 'ios',
          )
        } else {
          visit(channel.expoSwift)
          visit(channel.expoKotlin)
          visit(channel.nitro)
          visit(channel.oneSDK)
          visit(channel.turbo)
        }
        for (const descriptor of extractAssetDescriptors(source)) {
          if (!descriptor.httpServerLocation) continue
          const directory = new URL(descriptor.httpServerLocation, channel.bundleUrl)
          const packaged =
            '/__peach/app-assets/' +
            createHash('sha256').update(directory.href).digest('hex')
          for (const scale of descriptor.scales) {
            const filename = metroAssetScaleFilename(
              descriptor.name,
              descriptor.type,
              scale,
            )
            const asset = await fetch(`${directory.href.replace(/\/$/, '')}/${filename}`)
            if (!asset.ok) throw new Error(`app asset ${filename}: HTTP ${asset.status}`)
            route(
              `${packaged}/${filename}`,
              new Uint8Array(await asset.arrayBuffer()),
              asset.headers.get('content-type') ?? 'application/octet-stream',
            )
          }
          source = source.replaceAll(
            JSON.stringify(descriptor.httpServerLocation),
            JSON.stringify(packaged),
          )
        }
        // footers (the native asset catalog among them) name release files by
        // absolute url; the release server is gone once the package launches
        const releaseBase = new URL('.', channel.bundleUrl).href
        for (const [, url] of source.matchAll(/"(https?:\/\/[^"\\\s]+)"/g))
          if (url?.startsWith(releaseBase)) resources.add(url)
        for (const url of resources) {
          const asset = await fetch(url)
          if (!asset.ok) throw new Error(`native app resource: HTTP ${asset.status}`)
          const resource = new Uint8Array(await asset.arrayBuffer())
          if (icuUrls.has(url) && !isSwiftIcuPacked(resource))
            throw new Error(
              `${url} is not a version 1 packed swift icu file; the release was published by an older peachsim than this cli, so publish it again`,
            )
          const packaged =
            '/__peach/app-assets/' +
            createHash('sha256').update(url).digest('hex') +
            path.extname(new URL(url).pathname)
          route(
            packaged,
            resource,
            asset.headers.get('content-type') ?? 'application/octet-stream',
          )
          source = source.replaceAll(JSON.stringify(url), JSON.stringify(packaged))
        }
        if (!icon) {
          const artwork = await fetch(channel.iconUrl)
          if (!artwork.ok) throw new Error(`app icon: HTTP ${artwork.status}`)
          icon = path.join(scratch, 'icon.png')
          fs.writeFileSync(icon, Buffer.from(await artwork.arrayBuffer()))
        }
        launchUrl = await routeBundle('/__peach/app.js', await prepareBundle(source))
        // the project's ios catalog travels with the launch, its images
        // routed below
        const catalog = configuredProject
          ? await discoverAppCatalog(configuredProject.appDir, origin)
          : null
        if (catalog) {
          const url = new URL(launchUrl)
          url.searchParams.set(
            'appCatalog',
            getCliRuntime().engine_app_catalog_wire.encodeAppCatalogWire(catalog),
          )
          launchUrl = url.href
        }
      } else if (local?.isDirectory()) {
        const { snapshotOneDevBundle, prepareBundleChannel } =
          await import('../../src/bundle-channel.mjs')
        const snapshot = await snapshotOneDevBundle(
          path.resolve(target),
          {},
          // the project's own node: a notarized host's node refuses the
          // project's ad hoc signed native addons under library validation.
          { platforms: ['ios'], runtimeExecutable: 'node' },
        )
        const snapshotIcon = path.join(scratch, 'channel-icon.png')
        execFileSync(
          '/usr/bin/sips',
          [
            '-s',
            'format',
            'png',
            icon ? path.resolve(icon) : path.join(host, 'Contents/Resources/Peach.icns'),
            '--out',
            snapshotIcon,
          ],
          { stdio: 'ignore' },
        )
        const release = await prepareBundleChannel({
          prefix: 'app',
          publicOrigin: origin,
          sourceSha: createHash('sha1')
            .update(snapshot.platforms[0].bundle)
            .digest('hex'),
          runtimeVersion: '1',
          name,
          icon: fs.readFileSync(snapshotIcon),
          ...snapshot,
        })
        const channel = release.channels[0]
        for (const object of channel.objects) {
          const bytes = object.key.endsWith('/bundle.js')
            ? Buffer.from(await prepareBundle(object.bytes.toString('utf8')))
            : object.bytes
          route('/' + object.key, bytes, object.contentType)
        }
        launchUrl = await buildShellUrl(channel.metadata.bundleUrl, origin, {
          bridgePort: 65534,
          resolvedBundle: {
            bundleUrl: channel.metadata.bundleUrl,
            port: 65534,
            framework: 'one',
          },
          project: resolveAppProject(target),
          offline: true,
          hot: false,
        })
      } else if (local?.isFile()) {
        const bundle = await stagePrebuiltBundle(
          path.resolve(target),
          65534,
          async (source) =>
            prepareBundle(
              configuredProject
                ? await configureProjectBundle(source, configuredProject, 'ios')
                : source,
            ),
        )
        launchUrl = await buildShellUrl(bundle.bundleUrl, origin, {
          bridgePort: 65534,
          resolvedBundle: bundle,
          project: configuredProject,
          offline: true,
          hot: false,
        })
      } else {
        launchUrl = await buildShellUrl(target, origin, {
          bridgePort: 65534,
          hot: false,
          project: configuredProject,
        })
        requiresServer =
          new URL(launchUrl).searchParams.has('bundle') ||
          new URL(launchUrl).pathname.startsWith('/rn/')
        if (!icon) {
          const opened = await resolveAppProjectForBundleUrl(
            new URL(launchUrl).searchParams.get('bundle') ?? undefined,
          )
          if (opened) icon = await projectIcon(opened.appDir, scratch)
        }
      }
      if (configuredProject && !values.has('--splash')) {
        const splash = new URL(launchUrl).searchParams.get('appSplash')
        const spec = splash ? parseAppSplashWire(splash) : null
        if (spec)
          for (const image of splashImageUrls(spec)) {
            const pathname = new URL(image).pathname
            if (!pathname.startsWith('/assets/'))
              throw new Error('app splash must name a project asset')
            const file = path.resolve(
              configuredProject.appDir,
              decodeURIComponent(pathname.slice('/assets/'.length)),
            )
            if (!file.startsWith(configuredProject.appDir + path.sep))
              throw new Error('app splash is outside its project')
            route(pathname, fs.readFileSync(file), splashImageContentType(image))
          }
      }
      if (values.has('--splash')) {
        const url = new URL(launchUrl)
        const image = stageHostBytes(
          fs.readFileSync(path.resolve(values.get('--splash')!)),
          origin,
          path.extname(values.get('--splash')!),
        )
        const { encodeAppSplashWire } = await import('../app-splash')
        url.searchParams.set(
          'appSplash',
          encodeAppSplashWire({
            source: 'one-native',
            imageUrl: image,
            backgroundColor: '#ffffff',
          }),
        )
        launchUrl = url.href
      }
      if (icon) {
        const png = path.join(scratch, 'home-icon.png')
        execFileSync(
          '/usr/bin/sips',
          ['-s', 'format', 'png', path.resolve(icon), '--out', png],
          { stdio: 'ignore' },
        )
        iconUrl = route('/__peach/home-icon.png', fs.readFileSync(png), 'image/png')
      }
      return stageHostLaunchMetadata(new URL(launchUrl), origin)
    })
    execFileSync('/usr/bin/ditto', [host, temporary])
    const contents = path.join(temporary, 'Contents')
    const resources = path.join(contents, 'Resources')
    const plist = path.join(contents, 'Info.plist')
    const hostInfo: unknown = JSON.parse(
      execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', plist], {
        encoding: 'utf8',
      }),
    )
    if (!isRecord(hostInfo) || typeof hostInfo.CFBundleExecutable !== 'string')
      throw new Error('native host has no executable')
    const hostExecutable = hostInfo.CFBundleExecutable
    fs.cpSync(runtime, path.join(resources, 'runtime'), {
      recursive: true,
      dereference: true,
    })
    fs.copyFileSync(cli, path.join(resources, 'bin', 'peach'))
    fs.mkdirSync(path.join(resources, 'payload'))
    const relocatableFiles: string[] = []
    for (const [file, source] of captured.files) {
      const bytes = fs.readFileSync(source)
      if (
        bytes.includes(Buffer.from('127.0.0.1')) &&
        new RegExp(APP_PACKAGE_ADDRESS_PATTERN, 'i').test(bytes.toString('utf8'))
      )
        relocatableFiles.push(file)
      fs.copyFileSync(source, path.join(resources, 'payload', file))
    }
    const manifest: AppPackageManifest = {
      schemaVersion: 1,
      buildId: randomUUID(),
      identifier,
      name,
      origin,
      hostExecutable,
      runtimeVersion,
      launchUrl: captured.value,
      iconUrl,
      defaults,
      launchEnvironmentFiles,
      relocatableFiles,
      routes,
      requiresServer,
    }
    fs.writeFileSync(path.join(resources, 'peach-app.json'), JSON.stringify(manifest))
    fs.writeFileSync(path.join(resources, 'app-launcher.cjs'), packagedAppLauncher)
    // launchd refuses a script executable beside a mach-o when the plist sets LSEnvironment
    // (posix error 162), so the launcher exports the host's environment instead
    const exports = Object.entries(
      isRecord(hostInfo.LSEnvironment) ? hostInfo.LSEnvironment : {},
    )
      .map(
        ([key, value]) => `export ${key}='${String(value).replaceAll("'", `'\\''`)}'\n`,
      )
      .join('')
    fs.writeFileSync(
      path.join(contents, 'MacOS', 'PeachApp'),
      `#!/bin/sh\n${exports}exec "$(dirname "$0")/../Frameworks/node" "$(dirname "$0")/../Resources/app-launcher.cjs" "$@"\n`,
      { mode: 0o755 },
    )
    const bundleInfo: Record<string, unknown> = {
      ...hostInfo,
      CFBundleExecutable: 'PeachApp',
      CFBundleIdentifier: identifier,
      CFBundleName: name,
      CFBundleDisplayName: name,
    }
    for (const key of ['CFBundleURLTypes', 'LSEnvironment', 'SUFeedURL', 'SUPublicEDKey'])
      delete bundleInfo[key]
    fs.writeFileSync(plist, JSON.stringify(bundleInfo))
    execFileSync('/usr/bin/plutil', ['-convert', 'xml1', plist])
    if (icon) {
      const iconset = path.join(scratch, 'App.iconset')
      fs.mkdirSync(iconset)
      for (const size of [16, 32, 128, 256, 512]) {
        execFileSync(
          '/usr/bin/sips',
          [
            '-s',
            'format',
            'png',
            '-z',
            String(size),
            String(size),
            path.resolve(icon),
            '--out',
            path.join(iconset, `icon_${size}x${size}.png`),
          ],
          { stdio: 'ignore' },
        )
        execFileSync(
          '/usr/bin/sips',
          [
            '-s',
            'format',
            'png',
            '-z',
            String(size * 2),
            String(size * 2),
            path.resolve(icon),
            '--out',
            path.join(iconset, `icon_${size}x${size}@2x.png`),
          ],
          { stdio: 'ignore' },
        )
      }
      execFileSync('/usr/bin/iconutil', [
        '-c',
        'icns',
        iconset,
        '-o',
        path.join(resources, 'Peach.icns'),
      ])
    }
    // each binary keeps the entitlements the host release gave it
    const entitlementsOf = (relative: string) => {
      const file = path.join(scratch, `${relative.replaceAll('/', '-')}.entitlements`)
      fs.writeFileSync(
        file,
        execFileSync('/usr/bin/codesign', [
          '--display',
          '--entitlements',
          '-',
          '--xml',
          path.join(host, 'Contents', relative),
        ]),
      )
      return file
    }
    const appEntitlements = entitlementsOf(`MacOS/${hostExecutable}`)
    const sign = (target: string, entitlements?: string) =>
      execFileSync('/usr/bin/codesign', [
        '--force',
        '--sign',
        identity ?? '-',
        ...(identity ? ['--options', 'runtime', '--timestamp'] : []),
        ...(entitlements ? ['--entitlements', entitlements] : []),
        target,
      ])
    if (identity) {
      // the release order of the host's own signing: every nested binary, then
      // nested bundles deepest first, then the entitled binaries and the app
      const files = fs
        .readdirSync(contents, { recursive: true, withFileTypes: true })
        .filter((entry) => entry.isFile())
        .map((entry) => path.join(entry.parentPath, entry.name))
      for (const file of files.sort((a, b) => b.length - a.length)) {
        const head = Buffer.alloc(4)
        const fd = fs.openSync(file, 'r')
        const read = fs.readSync(fd, head, 0, 4, 0)
        fs.closeSync(fd)
        // a thin arm64 or a universal mach-o
        if (read === 4 && [0xcffaedfe, 0xcafebabe].includes(head.readUInt32BE(0)))
          sign(file)
      }
      for (const bundle of fs
        .readdirSync(contents, { recursive: true, withFileTypes: true })
        .filter(
          (entry) => entry.isDirectory() && /\.(app|xpc|framework)$/.test(entry.name),
        )
        .map((entry) => path.join(entry.parentPath, entry.name))
        .sort((a, b) => b.length - a.length))
        sign(bundle)
      sign(path.join(resources, 'bin', 'peach'), entitlementsOf('Resources/bin/peach'))
      sign(path.join(contents, 'Frameworks', 'node'), entitlementsOf('Frameworks/node'))
    } else sign(path.join(resources, 'bin', 'peach'), appEntitlements)
    // the launcher script is the bundle executable, so the host binary
    // needs its jit entitlements signed on directly
    sign(path.join(contents, 'MacOS', hostExecutable), appEntitlements)
    await primeCodeCache(temporary, path.join(scratch, 'prime-home'))
    sign(temporary, identity ? appEntitlements : undefined)
    execFileSync('/usr/bin/codesign', ['--verify', '--deep', '--strict', temporary])
    const notarize = (file: string) => {
      const result: unknown = JSON.parse(
        execFileSync(
          '/usr/bin/xcrun',
          [
            'notarytool',
            'submit',
            file,
            '--keychain-profile',
            notaryProfile!,
            '--wait',
            '--output-format',
            'json',
          ],
          { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] },
        ),
      )
      if (!isRecord(result) || result.status !== 'Accepted') {
        const id = isRecord(result) && typeof result.id === 'string' ? result.id : ''
        if (id)
          execFileSync(
            '/usr/bin/xcrun',
            ['notarytool', 'log', id, '--keychain-profile', notaryProfile!],
            { stdio: 'inherit' },
          )
        throw new Error(
          `notarization did not accept ${path.basename(file)}: ${JSON.stringify(result)}`,
        )
      }
    }
    const staple = (file: string) =>
      execFileSync('/usr/bin/xcrun', ['stapler', 'staple', file], { stdio: 'ignore' })
    const zip = (destination: string) =>
      execFileSync('/usr/bin/ditto', [
        '-c',
        '-k',
        '--sequesterRsrc',
        '--keepParent',
        temporary,
        destination,
      ])
    if (notaryProfile) {
      const submission = path.join(scratch, 'notarization.zip')
      zip(submission)
      notarize(submission)
      staple(temporary)
    }
    if (archive === '.app') fs.renameSync(temporary, output)
    else if (archive === '.zip') zip(output)
    else {
      // the disk image opens to the app beside an Applications shortcut
      fs.symlinkSync('/Applications', path.join(staging, 'Applications'))
      execFileSync(
        '/usr/bin/hdiutil',
        ['create', '-volname', name, '-srcfolder', staging, '-format', 'UDZO', output],
        { stdio: 'ignore' },
      )
      if (identity)
        execFileSync('/usr/bin/codesign', [
          '--force',
          '--sign',
          identity,
          '--timestamp',
          output,
        ])
      if (notaryProfile) {
        notarize(output)
        staple(output)
      }
    }
    console.log(output)
    if (requiresServer)
      console.error(
        'This app reconnects to its configured server; keep that server running.',
      )
  } finally {
    fs.rmSync(staging, { recursive: true, force: true })
    fs.rmSync(scratch, { recursive: true, force: true })
  }
}
