// prepare Expo's own CocoaPods workspace in a private cache on the Mac.
import { execFile, execFileSync, spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
import { promisify } from 'node:util'
import { detectPackageManager } from '../cli/commands/detect'
import { teamMachineInstalled } from './admitted-mac-build'
import { workspaceExclusion, type WorkspaceExclusion } from './expo-workspace-exclusion'
import { cacheDir } from './home-paths'
import { failedOutputLine } from './native-failure-output'
import { requireNativeGit } from './native-git'
import { prepareOneSDKSources } from './one-sdk-preparation'
import { portableExpoWorkspace } from './portable-expo-workspace'
import {
  reapRetiredCacheDirectory,
  removeRetiredDirectory,
} from './retired-cache-directory'
import {
  withCocoaPodsCacheLock,
  withSwiftRootLock,
  type SwiftRootLease,
} from './swift-root-lock'
import { sharedCacheDir } from './swift-toolchain'
import { findWorkspaceRoot } from './workspace-root'
import { resolveXcodeSwiftPackages, selectXcodeWorkspace } from './xcode-project'

// install scripts that write git hooks must never reach the user's global hooks path
const isolatedGitEnv = {
  GIT_CONFIG_GLOBAL: '/dev/null',
  GIT_CONFIG_SYSTEM: '/dev/null',
}

// CocoaPods refuses a non UTF-8 locale, so even its version probe names one.
const utf8Env = { ...process.env, LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' }

// react native uses these existing CocoaPods inputs to select source targets
// or its prebuilt frameworks; each choice needs its own prepared workspace.
export function reactNativePodsEnvironment() {
  return {
    RCT_USE_PREBUILT_RNCORE: process.env.RCT_USE_PREBUILT_RNCORE,
    RCT_USE_RN_DEP: process.env.RCT_USE_RN_DEP,
  }
}

// install from the lockfile that describes the app's dependencies. a manifest
// can retain a different packageManager after the project changes managers.
function workspacePackageManager(
  root: string,
  declared: unknown,
  excluded: WorkspaceExclusion,
): string {
  const manager = typeof declared === 'string' ? declared : detectPackageManager(root)
  const locks = [
    { manager: 'bun', files: ['bun.lock', 'bun.lockb'] },
    { manager: 'pnpm', files: ['pnpm-lock.yaml'] },
    { manager: 'yarn', files: ['yarn.lock'] },
    { manager: 'npm', files: ['package-lock.json'] },
  ].filter(({ files }) =>
    files.some((file) => !excluded(file) && fs.existsSync(path.join(root, file))),
  )
  if (locks.length !== 1) return manager
  const lockedManager = locks[0]!.manager
  return manager === lockedManager || manager.startsWith(`${lockedManager}@`)
    ? manager
    : lockedManager
}

// the files whose content steers install, prebuild and pod install: manifests,
// lockfiles, app and plugin config, patches and native project files.
const NATIVE_CONFIG_FILE =
  /(^|\/)(package\.json|bun\.lockb?|package-lock\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|\.yarnrc\.yml|\.npmrc|app\.json|app\.config\.[cm]?[jt]s|Podfile(\.lock|\.properties)?|expo-module\.config\.json|react-native\.config\.[cm]?[jt]s|\.nvmrc|\.tool-versions|\.?mise(?:\.[^/]+)?\.toml)$|\.(podspec|patch|plist|entitlements|xcconfig|pbxproj|storyboard|xib|gradle|rb)$|(^|\/)(plugins|patches)\//
// native sources steer pod install by existing, not by content: an edit to one
// is copied into the prepared workspace, an added or removed one rebuilds it.
const NATIVE_SOURCE_FILE = /\.(swift|mm?|hpp?|c|cc|cpp|kt|java)$/
const NATIVE_PACKAGE_ENTRY =
  /^(ios|android|.*\.podspec|expo-module\.config\.json|react-native\.config\.[cm]?[jt]s|app\.plugin\.[cm]?js)$/

// every file the native prepare can read, plus the toolchain that reads it.
// node_modules stays out: the js install reconciles it with the hashed
// lockfiles, and the discovery cache keys the live native inventory separately.
// the walk yields so the bridge that runs it keeps answering its other requests.
export async function hashExpoWorkspace(app: string, signal?: AbortSignal) {
  if (process.platform !== 'darwin') {
    const source = await hashExpoSourceWorkspace(app, signal)
    const prepared = await portableExpoWorkspace(app, source.hash, signal)
    return {
      root: source.root,
      hash: createHash('sha256')
        .update(`${source.hash}\0${prepared.identity}`)
        .digest('hex'),
    }
  }
  const { root, hash } = await hashWorkspaceInputs(app, true, signal)
  return { root, hash }
}

// the portable producer records the app inputs separately from its Mac
// toolchain, so a Linux consumer can verify the same source without Xcode.
export async function hashExpoSourceWorkspace(app: string, signal?: AbortSignal) {
  const { root, hash } = await hashWorkspaceInputs(app, true, signal, true)
  return { root, hash }
}

// a portable producer cannot claim the live app's hash unless the prepared
// copy actually holds those bytes, including files outside the native graph.
export async function verifyExpoWorkspaceCopy(app: string, work: string) {
  const root = findWorkspaceRoot(app)
  const excluded = await workspaceExclusion(
    root,
    true,
    linkedPackageDirectories(root, app),
  )
  const walk = (directory: string) => {
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
      const file = path.join(directory, entry.name)
      const relative = path.relative(root, file)
      if (excluded(relative, entry.isDirectory())) continue
      const copy = path.join(work, relative)
      if (entry.isDirectory()) walk(file)
      else if (entry.isSymbolicLink()) {
        const target = fs.realpathSync(file)
        const within = path.relative(root, target)
        if (
          within === '..' ||
          within.startsWith(`..${path.sep}`) ||
          path.isAbsolute(within)
        )
          throw new Error(`Expo source link escapes the workspace: ${relative}`)
        if (
          !fs.lstatSync(copy).isSymbolicLink() ||
          fs.readlinkSync(file) !== fs.readlinkSync(copy)
        )
          throw new Error(`Expo source link differs from preparation: ${relative}`)
      } else if (entry.isFile()) {
        if (!fs.existsSync(copy) || !fs.readFileSync(file).equals(fs.readFileSync(copy)))
          throw new Error(`Expo source differs from preparation: ${relative}`)
      }
    }
  }
  walk(root)
}

function pnpmStoreArgs(root: string) {
  const modules = path.join(root, 'node_modules', '.modules.yaml')
  if (!fs.existsSync(modules)) return []
  const store = /^\s*"?storeDir"?:\s*["']?([^"'\n,]+)/m.exec(
    fs.readFileSync(modules, 'utf8'),
  )
  return store ? ['--store-dir', store[1]!] : []
}

function linkedPackageDirectories(root: string, app: string) {
  const appRelative = path.relative(root, app)
  return localPackageDirectories(root, app).filter(
    (directory) => directory !== '' && directory !== appRelative,
  )
}

// the local packages the app links, found through the installed workspace
// links. the prepare copies the whole repository, but only these directories,
// the repository root and its patches decide the pods, so an edit to an
// unrelated package keeps the prepared workspace.
function localPackageDirectories(root: string, app: string) {
  const directories = new Set<string>()
  const visit = (directory: string) => {
    const relative = path.relative(root, directory)
    if (directories.has(relative)) return
    directories.add(relative)
    const manifest = JSON.parse(
      fs.readFileSync(path.join(directory, 'package.json'), 'utf8'),
    )
    for (const name of Object.keys({
      ...manifest.dependencies,
      ...manifest.devDependencies,
      ...manifest.peerDependencies,
      ...manifest.optionalDependencies,
    })) {
      for (let at = directory; ; at = path.dirname(at)) {
        const link = path.join(at, 'node_modules', name)
        if (fs.existsSync(link)) {
          const target = fs.realpathSync(link)
          const within = path.relative(root, target)
          if (
            !within.startsWith('..') &&
            !within.split(path.sep).includes('node_modules') &&
            fs.existsSync(path.join(target, 'package.json'))
          )
            visit(target)
          break
        }
        if (at === root) break
      }
    }
  }
  visit(app)
  return [...directories]
}

// the prepare reads only the native subset, so it skips the bytes of every
// other file: a monorepo's sources run to hundreds of megabytes per launch.
async function hashWorkspaceInputs(
  app: string,
  everyByte: boolean,
  signal?: AbortSignal,
  sourceOnly = false,
  podsEnvironment = reactNativePodsEnvironment(),
): Promise<{
  root: string
  appRelative: string
  hash: string
  // the subset of inputs that decides the prepared workspace
  nativeHash: string
  excluded: WorkspaceExclusion
}> {
  const root = findWorkspaceRoot(app)
  const excluded = await workspaceExclusion(
    root,
    sourceOnly,
    linkedPackageDirectories(root, app),
  )
  const appRelative = path.relative(root, app)
  const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
  const hash = createHash('sha256')
  const native = createHash('sha256')
  const nativeDirectories = localPackageDirectories(root, app)
  // a local package that builds no native code does not steer the prepare by
  // its own version, so a release bump of it and of its lockfile entry keeps
  // the prepared workspace. the app keeps its version: expo config reads it.
  // a workspace package the app does not link has no say at all, and the
  // release bumps one on every landing.
  const versionFree = new Set(
    nativeDirectories
      .filter((directory) => directory !== appRelative && directory !== '')
      .filter(
        (directory) =>
          !fs
            .readdirSync(path.join(root, directory))
            .some((name) => NATIVE_PACKAGE_ENTRY.test(name)),
      )
      .map((directory) => directory.split(path.sep).join('/')),
  )
  const versioned = new Set(
    nativeDirectories
      .map((directory) => directory.split(path.sep).join('/'))
      .filter((directory) => !versionFree.has(directory)),
  )
  const nativeConfigBytes = (posix: string, bytes: Buffer) => {
    const directory = path.posix.dirname(posix)
    if (path.posix.basename(posix) === 'package.json' && versionFree.has(directory)) {
      const { version: _version, ...manifest } = JSON.parse(bytes.toString('utf8'))
      return JSON.stringify(manifest)
    }
    if (posix !== 'bun.lock') return bytes
    let entry: string | null = null
    let workspaces = false
    return bytes
      .toString('utf8')
      .split('\n')
      .filter((line) => {
        if (/^ {2}"[^"]+": [{[]$/.test(line)) workspaces = line === '  "workspaces": {'
        const opened = /^ {4}"([^"]+)": \{$/.exec(line)
        if (workspaces && opened) entry = opened[1] ?? null
        return !(
          workspaces &&
          entry &&
          !versioned.has(entry) &&
          /^ {6}"version": "[^"]*",$/.test(line)
        )
      })
      .join('\n')
  }
  const steersNative = (relative: string) =>
    !relative.includes(path.sep) ||
    relative.startsWith(`patches${path.sep}`) ||
    nativeDirectories.some(
      (directory) =>
        directory === '' ||
        relative === directory ||
        relative.startsWith(directory + path.sep),
    )
  const walk = async (directory: string) => {
    const entries = await fs.promises.readdir(directory, { withFileTypes: true })
    for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
      signal?.throwIfAborted()
      const file = path.join(directory, entry.name)
      const relative = path.relative(root, file)
      if (excluded(relative, entry.isDirectory())) continue
      hash.update(`${relative}\0`)
      if (entry.isSymbolicLink()) {
        const link = `link\0${await fs.promises.readlink(file)}\0`
        hash.update(link)
        if (steersNative(relative)) native.update(`${relative}\0${link}`)
      } else if (entry.isDirectory()) {
        hash.update('directory\0')
        await walk(file)
      } else if (entry.isFile()) {
        const posix = relative.split(path.sep).join('/')
        if (NATIVE_CONFIG_FILE.test(posix)) {
          const bytes = await fs.promises.readFile(file)
          if (everyByte) hash.update(`file\0${bytes.length}\0`).update(bytes)
          if (steersNative(relative))
            native.update(`${posix}\0`).update(nativeConfigBytes(posix, bytes))
        } else {
          if (everyByte) {
            const bytes = await fs.promises.readFile(file)
            hash.update(`file\0${bytes.length}\0`).update(bytes)
          }
          if (NATIVE_SOURCE_FILE.test(posix) && steersNative(relative))
            native.update(`${posix}\0`)
        }
      }
    }
  }
  await walk(root)
  if (sourceOnly) {
    hash.update(`\0${appRelative}\0`)
    return {
      root,
      appRelative,
      hash: hash.digest('hex'),
      nativeHash: native.digest('hex'),
      excluded,
    }
  }
  // cocoapods and xcode exist only on a Mac; elsewhere only the prebuild stage runs
  const execFileAsync = promisify(execFile)
  const mac =
    process.platform === 'darwin'
      ? await Promise.all([
          // runner-toolchain-platform: darwin
          execFileAsync('pod', ['--version'], { env: utf8Env, signal }).catch(
            (cause: unknown) => {
              throw new Error('CocoaPods is required to install source dependencies', {
                cause,
              })
            },
          ),
          // runner-toolchain-platform: darwin
          execFileAsync('xcodebuild', ['-version'], { env: utf8Env, signal }),
        ]).then(([pod, xcode]) => ({ podVersion: pod.stdout, xcode: xcode.stdout }))
      : {}
  const pinnedNode =
    typeof manifest.engines?.node === 'string' &&
    /^\d+(\.\d+){0,2}$/.test(manifest.engines.node)
      ? `node@${manifest.engines.node}`
      : null
  const toolchain = JSON.stringify({
    preparation: 7,
    appRelative,
    ...mac,
    node: (
      await execFileAsync(
        pinnedNode ? 'mise' : 'node',
        pinnedNode ? ['exec', pinnedNode, '--', 'node', '--version'] : ['--version'],
        { cwd: root, signal },
      )
    ).stdout.trim(),
    packageManager: workspacePackageManager(root, manifest.packageManager, excluded),
    podsEnvironment,
  })
  hash.update(toolchain)
  native.update(toolchain)
  return {
    root,
    appRelative,
    hash: hash.digest('hex'),
    nativeHash: native.digest('hex'),
    excluded,
  }
}

// each prepared workspace copies the app's repository with its installed
// dependencies and pods, often many gigabytes, and every source edit hashes to
// a new one. a prepare keeps the workspace it returns plus the newest other
// complete ones and retires the rest; a workspace used within the grace window
// always stays. retirement takes the preparation lock without waiting, so a
// workspace being prepared stays too. a retired tree leaves the address space
// by rename before it is deleted, so a later prepare sees a miss and rebuilds.
const KEPT_WORKSPACES = 2
const WORKSPACE_GRACE_MS = 3_600_000
// a prepare that died leaves an incomplete tree only a retry of its own hash
// would replace; no prepare runs for a day.
const ABANDONED_WORKSPACE_MS = 24 * 3_600_000
const RETIRED_PREFIX = '.retired-'

async function pruneExpoNativeWorkspaces(parent: string, keep: string) {
  const retire = (directory: string, used: number) =>
    withSwiftRootLock(
      directory,
      async () => {
        const retired = path.join(
          parent,
          `${RETIRED_PREFIX}${process.pid}-${path.basename(directory)}`,
        )
        // nested writes do not renew the root's mtime. the prepare lock must be
        // free before retirement, and a renewal since the scan keeps it too.
        if (fs.statSync(directory, { throwIfNoEntry: false })?.mtimeMs !== used) return
        try {
          fs.renameSync(directory, retired)
        } catch (error) {
          if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return
          throw error
        }
        removeRetiredDirectory(retired)
      },
      undefined,
      false,
    )
  const complete: { directory: string; used: number }[] = []
  for (const name of fs.readdirSync(parent)) {
    const directory = path.join(parent, name)
    if (name.startsWith(RETIRED_PREFIX)) {
      reapRetiredCacheDirectory(parent, name)
      continue
    }
    const used = fs.statSync(directory, { throwIfNoEntry: false })?.mtimeMs
    if (directory === keep || used === undefined) continue
    if (
      fs.existsSync(path.join(directory, '.peach-complete')) ||
      fs.existsSync(path.join(directory, '.peach-project-complete'))
    )
      complete.push({ directory, used })
    else if (Date.now() - used > ABANDONED_WORKSPACE_MS) await retire(directory, used)
  }
  for (const { directory, used } of complete
    .sort((a, b) => b.used - a.used)
    .slice(KEPT_WORKSPACES - 1))
    if (Date.now() - used > WORKSPACE_GRACE_MS) await retire(directory, used)
}

// an edit that leaves the native inputs alone lands in the prepared copy by
// stat, so a warm open reads no file it did not have to. installed
// dependencies are not hashed, so a copy that has yet to pass pod install also
// takes the files the app's tree gained since the copy: a native dependency's
// own install step (react-native-skia's install-skia) adds libraries pod install
// checks for. a newer source file replaces its copy; one the prepare wrote in
// the copy stays.
function syncChangedFiles(
  root: string,
  work: string,
  appRelative: string,
  excluded: WorkspaceExclusion,
  installed: boolean,
) {
  const copyIfNewer = (file: string, relative: string, newerOnly: boolean) => {
    const source = fs.statSync(file)
    const target = path.join(work, relative)
    const existing = fs.statSync(target, { throwIfNoEntry: false })
    // timestamp-preserving copies use Dates, which truncate fractional
    // milliseconds; compare at that same precision to avoid copying again.
    if (
      existing &&
      (newerOnly
        ? existing.mtime.getTime() >= source.mtime.getTime()
        : existing.size === source.size &&
          existing.mtime.getTime() === source.mtime.getTime())
    )
      return
    fs.mkdirSync(path.dirname(target), { recursive: true })
    // a tool already running from the copy (the autolinker) must never read a
    // truncated script, so the new bytes land by rename
    const staged = `${target}.${process.pid}.peach-sync`
    fs.copyFileSync(file, staged)
    fs.utimesSync(staged, source.atime, source.mtime)
    fs.renameSync(staged, target)
  }
  const walkInstalled = (directory: string) => {
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
      const file = path.join(directory, entry.name)
      if (entry.isDirectory()) walkInstalled(file)
      else if (entry.isFile()) copyIfNewer(file, path.relative(root, file), true)
    }
  }
  const sourceIos = fs.existsSync(path.join(root, appRelative, 'ios', 'Podfile'))
  const walk = (directory: string) => {
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
      const file = path.join(directory, entry.name)
      const relative = path.relative(root, file)
      if (
        installed &&
        entry.name === 'node_modules' &&
        entry.isDirectory() &&
        fs.existsSync(path.join(work, relative))
      ) {
        walkInstalled(file)
        continue
      }
      // the app's ios project is prebuild output, not a source
      if (
        excluded(relative, entry.isDirectory()) ||
        entry.isSymbolicLink() ||
        (!sourceIos && relative === path.join(appRelative, 'ios'))
      )
        continue
      if (entry.isDirectory()) walk(file)
      else if (entry.isFile()) {
        // the work key already hashes these bytes, and pod install rewrites
        // several of them (the project, the lock), so copying the source's
        // pre-install copy back would undo the install
        if (NATIVE_CONFIG_FILE.test(relative.split(path.sep).join('/'))) continue
        copyIfNewer(file, relative, false)
      }
    }
  }
  walk(root)
}

// a launch asks for the workspace from its swift, nitro and turbo routes at
// once; they share one prepare, and a caller that gives up leaves it running
// for the others.
const preparing = new Map<string, ReturnType<typeof prepareWorkspace>>()

// a prepare stays current until a file under its root changes outside the
// ignored paths. the filesystem reports each edit, so a launch with nothing
// edited since the last prepare skips the walk, the toolchain probes and the sync.
type RootWatch = { edits: number; excluded?: (relative: string) => boolean }
const watches = new Map<string, RootWatch>()
const current = new Map<
  string,
  {
    watch: RootWatch
    edits: number
    result: { app: string; work: string }
  }
>()

function watchRoot(root: string) {
  const existing = watches.get(root)
  if (existing) return existing
  const watch: RootWatch = { edits: 0 }
  const watcher = fs.watch(root, { recursive: true }, (_event, filename) => {
    const parts = filename?.split(path.sep) ?? []
    const { excluded } = watch
    // an event names the changed file, and the ignored set lists its directory
    if (
      excluded &&
      parts.some((_, index) => excluded(parts.slice(0, index + 1).join(path.sep)))
    )
      return
    watch.edits += 1
  })
  watcher.on('error', () => {
    watcher.close()
    watches.delete(root)
    watch.edits += 1
  })
  watcher.unref()
  watches.set(root, watch)
  return watch
}

export async function prepareExpoNativeWorkspace(
  app: string,
  signal?: AbortSignal,
  target?: string,
) {
  const prepared = await prepare(app, 'workspace', signal)
  const ios = path.join(prepared.app, 'ios')
  const workspaces = fs.readdirSync(ios).filter((name) => name.endsWith('.xcworkspace'))
  const workspace = selectXcodeWorkspace(ios, workspaces)
  if (!workspace) throw new Error(`expected one Expo workspace in ${ios}`)
  await resolveXcodeSwiftPackages(workspace, signal, target)
  return { ...prepared, workspace }
}

// cocoapods runs only on a Mac. elsewhere the real pod graph exists only when a
// prepared workspace is supplied; without one, installed modules compile from
// their own sources as app-local modules do.
export function nativeWorkspaceAvailable(): boolean {
  return (
    process.platform === 'darwin' || Boolean(process.env.PEACH_PREPARED_NATIVE_WORKSPACES)
  )
}

/** the app root whose ios directory the native compilers read: with the
 *  installed CocoaPods workspace where one can exist, otherwise the prebuilt
 *  Xcode project alone, which still declares the app's deployment target. */
export async function prepareNativeAppRoot(
  app: string,
  signal?: AbortSignal,
  target?: string,
) {
  return (
    nativeWorkspaceAvailable()
      ? await prepareExpoNativeWorkspace(app, signal, target)
      : await prepareExpoNativeProject(app, signal)
  ).app
}

// resource target membership is generated by prebuild, before CocoaPods runs.
export function prepareExpoNativeProject(app: string, signal?: AbortSignal) {
  return prepare(app, 'project', signal)
}

function prepare(app: string, stage: 'project' | 'workspace', signal?: AbortSignal) {
  const podsEnvironment = reactNativePodsEnvironment()
  const key = `${app}\0${stage}\0${JSON.stringify(podsEnvironment)}`
  const last = current.get(key)
  if (
    last &&
    last.watch.edits === last.edits &&
    (fs.existsSync(path.join(last.result.work, '.peach-complete')) ||
      (stage === 'project' &&
        fs.existsSync(path.join(last.result.work, '.peach-project-complete'))))
  ) {
    const now = new Date()
    fs.utimesSync(last.result.work, now, now)
    return Promise.resolve(last.result)
  }
  let shared = preparing.get(key)
  if (!shared) {
    shared = prepareWorkspace(app, stage, key, podsEnvironment).finally(() =>
      preparing.delete(key),
    )
    preparing.set(key, shared)
  }
  if (!signal) return shared
  signal.throwIfAborted()
  const prepared = shared
  return new Promise<Awaited<typeof prepared>>((resolve, reject) => {
    const abort = () =>
      reject(
        new Error('stopped waiting for the expo workspace', { cause: signal.reason }),
      )
    signal.addEventListener('abort', abort, { once: true })
    prepared
      .then(resolve, reject)
      .finally(() => signal.removeEventListener('abort', abort))
  })
}

// a workspace starts from the app's own installed dependencies, which the js
// install then reconciles with the lockfile: an installed tree that matches
// takes it under a second, where a fresh install fetches, links and runs every
// lifecycle script again. cp clones the trees eight packages at a time; a
// per-file copy from node takes several times as long, one cp per tree twice.
async function copyInstalledWorkspace(
  root: string,
  destination: string,
  excluded: WorkspaceExclusion,
) {
  const installed: string[] = []
  await fs.promises.cp(root, destination, {
    recursive: true,
    mode: fs.constants.COPYFILE_FICLONE,
    preserveTimestamps: true,
    verbatimSymlinks: true,
    filter: (source) => {
      const relative = path.relative(root, source)
      if (path.basename(source) === 'node_modules') installed.push(relative)
      return !excluded(relative)
    },
  })
  const entries = installed.flatMap((relative) => {
    const source = path.join(root, relative)
    if (fs.lstatSync(source).isSymbolicLink()) {
      fs.symlinkSync(fs.readlinkSync(source), path.join(destination, relative))
      return []
    }
    fs.mkdirSync(path.join(destination, relative))
    return fs
      .readdirSync(source)
      .filter((name) => name !== '.cache')
      .map((name) => path.join(relative, name))
  })
  const clone = async (): Promise<void> => {
    const relative = entries.pop()
    if (relative === undefined) return
    await promisify(execFile)('cp', [
      // -c clones on a Mac, as gnu cp already does where the filesystem can
      ...(process.platform === 'darwin' ? ['-c'] : []),
      '-R',
      '-p',
      path.join(root, relative),
      path.join(destination, relative),
    ])
    return clone()
  }
  await Promise.all(Array.from({ length: 8 }, clone))
}

// release producers prepare the already installed app. this preserves the
// exact dependency tree selected by a replay, including a staged package.
export async function prepareInstalledExpoWorkspace(app: string, work: string) {
  if (process.platform !== 'darwin')
    throw new Error('Expo workspace production requires a Mac')
  const root = findWorkspaceRoot(app)
  const excluded = await workspaceExclusion(
    root,
    true,
    linkedPackageDirectories(root, app),
  )
  const appRelative = path.relative(root, app)
  if (fs.existsSync(work))
    throw new Error(`prepared Expo workspace already exists: ${work}`)
  fs.mkdirSync(path.dirname(work), { recursive: true })
  return withSwiftRootLock(work, async (lease) => {
    await copyInstalledWorkspace(root, work, excluded)
    initializeWorkspaceGit(root, work)
    const preparedApp = path.join(work, appRelative)
    const manifest = JSON.parse(
      fs.readFileSync(path.join(preparedApp, 'package.json'), 'utf8'),
    )
    const run: NativeRun = (command, args, cwd, env = {}) =>
      runAdmitted(lease, command, args, cwd, env)
    const execute: NativeExecute = (args, cwd, env = {}) =>
      run(args[0]!, args.slice(1), cwd, env)
    await prepareNativeProject(
      preparedApp,
      manifest,
      'workspace',
      execute,
      run,
      (message) => console.error(`[expo-native-workspace] ${message}`),
    )
    fs.writeFileSync(path.join(work, '.peach-complete'), 'complete\n')
    const ios = path.join(preparedApp, 'ios')
    const workspaces = fs.readdirSync(ios).filter((name) => name.endsWith('.xcworkspace'))
    if (workspaces.length !== 1) throw new Error(`expected one Expo workspace in ${ios}`)
    return { app: preparedApp, workspace: path.join(ios, workspaces[0]!), work }
  })
}

// the copy's index lists the files its source checkout tracks, including ignored ones
// the project commits, so a postinstall that marks them with `git update-index` finds
// them. the entries reuse the source index's object ids: hashing or storing a monorepo's
// worth of blobs takes minutes, and nothing reads their contents from this repository
function trackedSourceEntries(root: string, work: string): string[] {
  const listed = spawnSync('git', ['ls-files', '--stage', '-z'], {
    cwd: root,
    env: { ...process.env, ...isolatedGitEnv },
    maxBuffer: 256 * 1024 * 1024,
  })
  if (listed.status !== 0) return []
  return listed.stdout
    .toString('utf8')
    .split('\0')
    .filter((entry) => {
      const tab = entry.indexOf('\t')
      return tab > 0 && fs.existsSync(path.join(work, entry.slice(tab + 1)))
    })
}

function initializeWorkspaceGit(root: string, work: string) {
  requireNativeGit()
  const env = { ...process.env, ...isolatedGitEnv }
  execFileSync('git', ['init', '--quiet'], { cwd: work, env })
  execFileSync(
    'git',
    [
      '-c',
      'user.name=peach',
      '-c',
      'user.email=peach@localhost',
      '-c',
      'commit.gpgsign=false',
      'commit',
      '--quiet',
      '--allow-empty',
      '--no-verify',
      '-m',
      'prepared workspace',
    ],
    { cwd: work, env },
  )
  const tracked = trackedSourceEntries(root, work)
  if (tracked.length > 0)
    execFileSync('git', ['update-index', '-z', '--index-info'], {
      cwd: work,
      env,
      input: tracked.join('\0'),
    })
}

async function prepareWorkspace(
  app: string,
  stage: 'project' | 'workspace',
  key: string,
  podsEnvironment: ReturnType<typeof reactNativePodsEnvironment>,
) {
  if (
    process.platform !== 'darwin' &&
    (stage === 'workspace' || nativeWorkspaceAvailable())
  ) {
    const source = await hashExpoSourceWorkspace(app)
    return portableExpoWorkspace(app, source.hash)
  }
  const started = performance.now()
  const report = (message: string) =>
    console.error(
      `[expo-native-workspace ${Math.round(performance.now() - started)}ms] ${message}`,
    )
  const watch = watchRoot(findWorkspaceRoot(app))
  const edits = watch.edits
  const { root, appRelative, nativeHash, excluded } = await hashWorkspaceInputs(
    app,
    false,
    undefined,
    false,
    podsEnvironment,
  )
  watch.excluded = excluded
  const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
  const appManifest = JSON.parse(fs.readFileSync(path.join(app, 'package.json'), 'utf8'))
  const work = path.join(sharedCacheDir(cacheDir()), 'expo-native-workspaces', nativeHash)
  report(`hashed ${root}`)
  const result = await withSwiftRootLock(work, async (lease) => {
    const marker = path.join(work, '.peach-complete')
    const projectMarker = path.join(work, '.peach-project-complete')
    const preparedApp = path.join(work, appRelative)
    const projectReady = fs.existsSync(marker) || fs.existsSync(projectMarker)
    if (projectReady) {
      syncChangedFiles(
        root,
        work,
        appRelative,
        excluded,
        stage === 'workspace' && !fs.existsSync(marker),
      )
      report(`reusing prepared workspace ${work}`)
    }
    if (!projectReady) {
      const partial = `${work}.${process.pid}.partial`
      await fs.promises.rm(partial, { recursive: true, force: true })
      await fs.promises.rm(work, { recursive: true, force: true })
      fs.mkdirSync(path.dirname(work), { recursive: true })
      await copyInstalledWorkspace(root, partial, excluded)
      fs.renameSync(partial, work)
      // a lifecycle script that installs git hooks needs a repository, and the copy gets its own.
      // an app config may read HEAD, so the repository carries one empty commit
      initializeWorkspaceGit(root, work)
      report('copied workspace')
    }
    // mise ties trust to a path. Carry only configs mise can load from the
    // original app and whose copied bytes still match, for this prepare only.
    const trustedConfigs = new Set<string>()
    for (const cwd of [root, app]) {
      // runner-toolchain-platform: darwin
      const result = spawnSync('mise', ['config', 'ls', '--json'], {
        cwd,
        encoding: 'utf8',
      })
      if (result.status !== 0) continue
      const configs: { path: string }[] = JSON.parse(result.stdout)
      for (const config of configs) {
        const relative = path.relative(root, config.path)
        if (relative.startsWith('..') || path.isAbsolute(relative)) continue
        const copy = path.join(work, relative)
        if (
          fs.existsSync(copy) &&
          fs.readFileSync(config.path).equals(fs.readFileSync(copy))
        )
          trustedConfigs.add(copy)
      }
    }
    const miseEnv = {
      MISE_TRUSTED_CONFIG_PATHS: [
        process.env.MISE_TRUSTED_CONFIG_PATHS,
        ...trustedConfigs,
      ]
        .filter(Boolean)
        .join(path.delimiter),
    }
    const run = (
      command: string,
      args: string[],
      cwd: string,
      env: Partial<NodeJS.ProcessEnv> = {},
    ) =>
      runAdmitted(lease, command, args, cwd, { ...miseEnv, ...podsEnvironment, ...env })
    const manager = workspacePackageManager(root, manifest.packageManager, excluded)
    const nodeVersion =
      typeof manifest.engines?.node === 'string' &&
      /^\d+(\.\d+){0,2}$/.test(manifest.engines.node)
        ? manifest.engines.node
        : null
    const prefix = nodeVersion ? ['mise', 'exec', `node@${nodeVersion}`, '--'] : []
    // a pinned bun installs into its own prefix: npm exec keeps one cached copy per spec, so a copy
    // installed without its postinstall (hosts that set ignore-scripts) would stay broken
    const bunPrefix = path.join(cacheDir(), 'package-managers', manager)
    const bunExecutable = path.join(bunPrefix, 'node_modules/.bin/bun')
    const install =
      manager === 'pnpm' || manager.startsWith('pnpm@')
        ? [
            'npx',
            '--yes',
            manager,
            'install',
            '--frozen-lockfile',
            // the copied node_modules link into the store pnpm chose on the app's volume
            ...pnpmStoreArgs(root),
          ]
        : manager === 'yarn' || manager.startsWith('yarn@')
          ? ['corepack', 'yarn', 'install', '--immutable']
          : manager === 'bun' || manager.startsWith('bun@')
            ? manager === 'bun'
              ? ['bun', 'install', '--frozen-lockfile']
              : [bunExecutable, 'install', '--frozen-lockfile']
            : // npm ci would delete the cloned tree before installing it again
              ['npm', 'install', '--no-audit', '--no-fund']
    // dependencies such as react-native-skia fetch their native binaries in a lifecycle
    // script, so a host-wide ignore-scripts must not reach the workspace install
    const installEnv = { npm_config_ignore_scripts: 'false' }
    const execute: NativeExecute = async (args, cwd, env = {}) => {
      const command = [...prefix, ...args]
      await run(command[0]!, command.slice(1), cwd, env)
    }
    const installedBun = manager.startsWith('bun@')
      ? spawnSync(bunExecutable, ['--version'], { encoding: 'utf8' })
      : null
    if (
      manager.startsWith('bun@') &&
      (installedBun?.status !== 0 || installedBun.stdout.trim() !== manager.slice(4))
    )
      await execute(
        [
          'npm',
          'install',
          '--prefix',
          bunPrefix,
          // the bun package ships a placeholder binary its postinstall replaces
          '--ignore-scripts=false',
          '--no-audit',
          '--no-fund',
          manager,
        ],
        work,
      )
    if (!projectReady) {
      // npm install keeps the cloned tree but can otherwise rewrite a stale lockfile.
      if (install[0] === 'npm' && fs.existsSync(path.join(work, 'package-lock.json'))) {
        await execute(
          ['npm', 'ci', '--dry-run', '--ignore-scripts', '--no-audit', '--no-fund'],
          work,
          installEnv,
        )
      }
      await execute(install, work, installEnv)
      report('installed js dependencies')
    }
    if (!projectReady) {
      await prepareNativeProject(
        preparedApp,
        appManifest,
        'project',
        execute,
        run,
        report,
      )
      fs.writeFileSync(projectMarker, 'complete\n')
    }
    if (stage === 'workspace' && !fs.existsSync(marker)) {
      await prepareNativeProject(
        preparedApp,
        appManifest,
        'workspace',
        execute,
        run,
        report,
      )
      fs.writeFileSync(marker, 'complete\n')
    }
    const now = new Date()
    fs.utimesSync(work, now, now)
    await pruneExpoNativeWorkspaces(path.dirname(work), work)
    return { app: preparedApp, work }
  })
  current.set(key, { watch, edits, result })
  return result
}

type NativeRun = (
  command: string,
  args: string[],
  cwd: string,
  env?: Record<string, string>,
) => Promise<void>
type NativeExecute = (
  args: string[],
  cwd: string,
  env?: Record<string, string>,
) => Promise<void>

type NativeProjectManifest = {
  dependencies?: Record<string, unknown>
  devDependencies?: Record<string, unknown>
}

export function declaresNativeDependency(manifest: NativeProjectManifest, name: string) {
  return (
    Object.hasOwn(manifest.dependencies ?? {}, name) ||
    Object.hasOwn(manifest.devDependencies ?? {}, name)
  )
}

async function prepareNativeProject(
  app: string,
  manifest: NativeProjectManifest,
  stage: 'project' | 'workspace',
  execute: NativeExecute,
  run: NativeRun,
  report: (message: string) => void,
) {
  const appRequire = createRequire(path.join(app, 'package.json'))
  // peach runs the new architecture only, and pods such as
  // react-native-paste-input refuse to evaluate without it
  const sourcePodEnv = { EXPO_USE_PRECOMPILED_MODULES: '0', RCT_NEW_ARCH_ENABLED: '1' }
  const declares = (name: string) => declaresNativeDependency(manifest, name)
  if (!fs.existsSync(path.join(app, 'ios', 'Podfile'))) {
    if (!declares('expo') && !declares('one'))
      throw new Error(
        `${app} has no ios/Podfile and declares neither expo nor one, so peach cannot generate an iOS project for it`,
      )
    const prebuild = declares('expo')
      ? [appRequire.resolve('expo/bin/cli'), 'prebuild']
      : [
          path.join(path.dirname(appRequire.resolve('one/package.json')), 'run.mjs'),
          'prebuild',
        ]
    await execute(
      ['node', ...prebuild, '--platform', 'ios', '--no-install'],
      app,
      sourcePodEnv,
    )
    report('prebuild done')
  }
  await prepareOneSDKSources(app)
  if (stage === 'project') return
  // react-native-skia leaves Dawn to react-native-webgpu whenever that package
  // is installed, but autolinking links it only into apps that declare it.
  const iosRoot = path.join(app, 'ios')
  // a Podfile that calls ensure_bundler! refuses a global CocoaPods
  const bundled = fs
    .readFileSync(path.join(iosRoot, 'Podfile'), 'utf8')
    .includes('ensure_bundler!')
  const podEnv = {
    ...sourcePodEnv,
    ...(declares('react-native-webgpu') ? {} : { RNSKIA_VENDOR_DAWN: '1' }),
  }
  stageCachedQuickCryptoOpenSsl(app)
  await withCocoaPodsCacheLock(async () => {
    if (bundled) {
      await run('bundle', ['install'], iosRoot, podEnv)
      await run('bundle', ['exec', 'pod', 'install'], iosRoot, podEnv)
    } else await run('pod', ['install'], iosRoot, podEnv)
  })
  report('pod install done')
}

function stageCachedQuickCryptoOpenSsl(app: string) {
  const root = findWorkspaceRoot(app)
  let packageDir: string | null = null
  for (let at = app; ; at = path.dirname(at)) {
    const candidate = path.join(at, 'node_modules', 'react-native-quick-crypto')
    if (fs.existsSync(path.join(candidate, 'QuickCrypto.podspec'))) {
      packageDir = candidate
      break
    }
    if (at === root || path.dirname(at) === at) break
  }
  if (!packageDir) return
  const opensslDir = path.join(packageDir, 'ios', 'openssl')
  if (fs.existsSync(path.join(opensslDir, 'quickcrypto_openssl_prefix.h'))) return
  const podspec = fs.readFileSync(path.join(packageDir, 'QuickCrypto.podspec'), 'utf8')
  const sha256 = /openssl_sha256\s*=\s*"([0-9a-f]{64})"/.exec(podspec)?.[1]
  if (!sha256) return
  const archive = path.join(cacheDir(), 'pod-archives', `${sha256}.zip`)
  if (
    !fs.existsSync(archive) ||
    createHash('sha256').update(fs.readFileSync(archive)).digest('hex') !== sha256
  )
    return
  fs.rmSync(opensslDir, { recursive: true, force: true })
  fs.mkdirSync(opensslDir, { recursive: true })
  execFileSync('unzip', ['-q', '-o', archive, '-d', opensslDir])
}

async function runAdmitted(
  lease: SwiftRootLease,
  command: string,
  args: string[],
  cwd: string,
  extraEnv: Partial<NodeJS.ProcessEnv>,
) {
  const admitted = teamMachineInstalled()
  const child = lease.spawn(
    admitted ? 'tm' : command,
    admitted
      ? ['window', 'run', 'heavy', '--local', '--wait', '--', command, ...args]
      : args,
    {
      cwd,
      env: {
        ...process.env,
        ...isolatedGitEnv,
        EXPO_NO_TELEMETRY: '1',
        LANG: 'en_US.UTF-8',
        LC_ALL: 'en_US.UTF-8',
        ...extraEnv,
      },
    },
  )
  const output: Buffer[] = []
  child.stdout.on('data', (bytes: Buffer) => output.push(bytes))
  child.stderr.on('data', (bytes: Buffer) => output.push(bytes))
  await new Promise<void>((resolve, reject) => {
    child.once('error', reject)
    child.once('close', (status, signal) => {
      if (status === 0) return resolve()
      const bytes = Buffer.concat(output)
      reject(
        new Error(
          `${command} exited ${status ?? signal}: ${bytes.toString('utf8')}\n${failedOutputLine(command, cwd, bytes)}`,
        ),
      )
    })
  })
}
