// a standard Expo app's native build from the prebuilt registry
// (specs/peach/swift/expo-native-compilation.md). preparing an Expo app's native
// workspace runs prebuild and pod install before the Expo Swift and TurboModule
// compilers can read it, which is most of a first open. our builder publishes
// both compilers' outputs for an app under a key of every native input, read
// before any preparation: Expo's own fingerprint of the app with its identity
// fields skipped, each native package's version and source tree, the runtime's
// answered packages, the Swift pin and these compilers' sources. an app whose
// inputs match fetches one metadata file and loads the published wasm; any
// other app prepares and compiles as before. identity values stay out of the
// artifact: an app reads its own from its prebuilt Xcode project, with the
// plist values pod install added.
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import plist from 'plist'
import { peachAnsweredNativePackages } from './answeredNativePackages'
import { expoNativeCompilerDigestValue } from './expo-native-compiler-digest'
import {
  declaresNativeDependency,
  hashExpoSourceWorkspace,
  prepareExpoNativeProject,
  reactNativePodsEnvironment,
} from './expo-native-workspace'
import {
  isExpoSwiftCompilationResult,
  type ExpoSwiftCompilationResult,
} from './expoSwiftContract'
import { isRecord } from './is-record'
import { readNativeAppIdentityFromXcodeTarget } from './native-app-identity-project'
import { readExpoConfigAsync } from './native-firebase-config'
import {
  NATIVE_PREBUILT_ORIGIN,
  nativeEntryKey,
  nativeEntryPrefix,
} from './native-prebuilt'
import { readTurboMetadata, type TurboCompiledModule } from './nitroContract'
import { packageTreeDigest } from './package-tree-digest'
import { swiftNativePin } from './swift-native-pin'
import {
  findXcodeProject,
  readXcodeAppTarget,
  type XcodeAppTarget,
} from './xcode-project'
import type { NativeAppIdentity } from './native-app-identity'

export const EXPO_NATIVE_ENTRY_NAME = 'ios'

// upstream's own skips for the values that differ between two copies of one
// app: versions, names, the bundle id and android package, schemes, the EAS
// project, icon and splash assets and `extra`. they reach the native build only
// through the app's identity, which each app reads from its own project.
const IDENTITY_SOURCE_SKIPS = 1 | 4 | 8 | 16 | 32 | 64 | 128 | 4096

type FingerprintSource = {
  type: string
  hash: string | null
  id?: string
  filePath?: string
  contents?: unknown
}

function readSources(value: unknown): FingerprintSource[] {
  const sources = isRecord(value) ? value.sources : null
  if (!Array.isArray(sources)) throw new Error('invalid Expo fingerprint')
  return sources.map((source) => {
    if (
      !isRecord(source) ||
      typeof source.type !== 'string' ||
      (source.hash !== null && typeof source.hash !== 'string')
    )
      throw new Error('invalid Expo fingerprint source')
    return {
      type: source.type,
      hash: source.hash,
      ...(typeof source.id === 'string' ? { id: source.id } : {}),
      ...(typeof source.filePath === 'string' ? { filePath: source.filePath } : {}),
      contents: source.contents,
    }
  })
}

// the package directory a fingerprint source under node_modules belongs to
function packageRootOf(appRoot: string, file: string): string | null {
  const parts = file.split('/')
  if (parts[0] !== 'node_modules') return null
  // pnpm keeps a package at node_modules/.pnpm/<id>/node_modules/<name>
  const at = parts.lastIndexOf('node_modules') + 1
  const end = at + (parts[at]?.startsWith('@') ? 2 : 1)
  return parts.length > end ? path.join(appRoot, ...parts.slice(0, end)) : null
}

/**
 * every input a standard Expo app's native build depends on, or null when the
 * app is not one the registry can serve: it keeps its own Xcode project, its
 * Expo has no fingerprint, or its config compiles app-owned inline modules.
 * the compiler digest and the Swift pin are among the inputs, so they name the
 * published entry on their own. `packages` maps each native package to its
 * directory: a hit compares their source trees with the ones the entry was
 * built from, which costs seconds, so a miss never pays it.
 */
export async function expoNativeInputs(appRoot: string): Promise<{
  inputs: Record<string, string>
  packages: Map<string, string>
} | null> {
  appRoot = fs.realpathSync(appRoot)
  if (findXcodeProject(path.join(appRoot, 'ios'))) return null
  const appRequire = createRequire(path.join(appRoot, 'package.json'))
  let fingerprintEntry: string
  try {
    fingerprintEntry = appRequire.resolve('@expo/fingerprint', {
      paths: [path.dirname(appRequire.resolve('expo/package.json'))],
    })
  } catch {
    return null
  }
  const fingerprint: unknown = appRequire(fingerprintEntry)
  const create = isRecord(fingerprint) ? fingerprint.createFingerprintAsync : null
  if (typeof create !== 'function') return null
  const sources = readSources(
    await create(appRoot, {
      platforms: ['ios'],
      sourceSkips: IDENTITY_SOURCE_SKIPS,
      debug: true,
      silent: true,
    }),
  )
  const config = sources.find((source) => source.id === 'expoConfig')?.contents
  const experiments =
    typeof config === 'string' ? JSON.parse(config)?.experiments : undefined
  if (isRecord(experiments) && experiments.inlineModules !== undefined) return null
  const packages = new Map<string, string>()
  const lines: string[] = []
  for (const source of sources) {
    lines.push(`${source.type}\0${source.id ?? source.filePath}\0${source.hash}`)
    // older fingerprints hash a native module's directory, newer ones its manifest
    const root =
      (source.type === 'package' || source.type === 'dir') && source.filePath
        ? packageRootOf(appRoot, source.filePath)
        : null
    if (!root) continue
    const manifest: unknown = JSON.parse(
      fs.readFileSync(path.join(root, 'package.json'), 'utf8'),
    )
    if (!isRecord(manifest) || typeof manifest.name !== 'string')
      throw new Error(`${root}: package has no name`)
    packages.set(manifest.name, root)
  }
  packages.set(
    'react-native',
    path.dirname(appRequire.resolve('react-native/package.json')),
  )
  return {
    inputs: {
      compiler: expoNativeCompilerDigestValue(),
      'swift-pin': JSON.stringify(swiftNativePin()),
      answered: JSON.stringify([...peachAnsweredNativePackages()].sort()),
      'pods-environment': JSON.stringify(reactNativePodsEnvironment()),
      fingerprint: createHash('sha256').update(lines.sort().join('\n')).digest('hex'),
    },
    packages,
  }
}

/** each native package's source tree, as an entry records them. */
export async function expoNativePackageDigests(
  packages: ReadonlyMap<string, string>,
): Promise<Record<string, string>> {
  const names = [...packages.keys()].sort()
  const digests = await Promise.all(
    names.map((name) => packageTreeDigest(packages.get(name)!)),
  )
  return Object.fromEntries(names.map((name, index) => [name, digests[index]!]))
}

export const expoNativeEntryUrl = (key: string, file: string) =>
  `${NATIVE_PREBUILT_ORIGIN}/${nativeEntryPrefix('expo', EXPO_NATIVE_ENTRY_NAME, key)}/${file}`

/** what an entry's metadata.json holds: both compilers' results with every url on the registry. */
export interface ExpoNativeEntry {
  // the Expo Swift result without the app's root id and identity, which the
  // app supplies; `identity` says whether the compiler's result carried one
  expoSwift: ExpoSwiftCompilationResult | null
  identity: boolean
  turbo: TurboCompiledModule | null
  // the source tree of each native package the entry was built from
  packages: Record<string, string>
  // the top-level values pod install writes into the app's own Info.plist
  infoPlist: Record<string, plist.PlistValue>
}

const isStringRecord = (value: unknown): value is Record<string, string> =>
  isRecord(value) && Object.values(value).every((item) => typeof item === 'string')

// the json an entry carries: what pod install writes is booleans and strings
function isPlistValue(value: unknown): value is plist.PlistValue {
  if (
    typeof value === 'string' ||
    typeof value === 'number' ||
    typeof value === 'boolean'
  )
    return true
  if (Array.isArray(value)) return value.every(isPlistValue)
  return isRecord(value) && Object.values(value).every(isPlistValue)
}

const isPlistArray = (value: plist.PlistValue): value is plist.PlistArray =>
  Array.isArray(value)

export function parsePlistDictionary(source: string): plist.PlistObject {
  const parsed = plist.parse(source)
  if (
    typeof parsed !== 'object' ||
    isPlistArray(parsed) ||
    parsed instanceof Date ||
    Buffer.isBuffer(parsed)
  )
    throw new Error('Info.plist is not a dictionary')
  return parsed
}

/**
 * the app's processed Info.plist as pod install leaves it: pod install
 * rewrites the file with its values added and every key sorted.
 */
export function installedInfoPlist(
  prebuilt: string,
  additions: Record<string, plist.PlistValue>,
): string {
  const merged = { ...parsePlistDictionary(prebuilt), ...additions }
  return plist.build(
    Object.fromEntries(
      Object.keys(merged)
        .sort()
        .map((key) => [key, merged[key]!]),
    ),
  )
}

export function readExpoNativeEntry(value: unknown): ExpoNativeEntry | null {
  if (!isRecord(value) || typeof value.identity !== 'boolean') return null
  if (!isStringRecord(value.packages) || !isRecord(value.infoPlist)) return null
  const expoSwift = value.expoSwift === null ? null : value.expoSwift
  if (expoSwift !== null && !isExpoSwiftCompilationResult(expoSwift)) return null
  const turbo = value.turbo === null ? null : readTurboMetadata(value.turbo)
  if (value.turbo !== null && !turbo) return null
  const infoPlist: Record<string, plist.PlistValue> = {}
  for (const [key, item] of Object.entries(value.infoPlist)) {
    if (!isPlistValue(item)) return null
    infoPlist[key] = item
  }
  return {
    expoSwift,
    identity: value.identity,
    turbo,
    packages: value.packages,
    infoPlist,
  }
}

// one process asks for each key once: an entry never changes, and the builder
// publishes a missing one for later processes.
const published = new Map<string, Promise<ExpoNativeEntry | null>>()
// the Expo Swift and TurboModule requests of one open look the app up together.
const lookups = new Map<string, Promise<ExpoNativeEntry | null>>()
// the fingerprint behind a lookup takes tens of seconds on every load; its
// answer stands while the app's hashed sources and evaluated config do.
const answers = new Map<string, { inputs: string; entry: ExpoNativeEntry | null }>()

async function answer(appRoot: string): Promise<ExpoNativeEntry | null> {
  if (findXcodeProject(path.join(appRoot, 'ios'))) return null
  const [source, config] = await Promise.all([
    hashExpoSourceWorkspace(appRoot),
    readExpoConfigAsync(appRoot),
  ])
  const inputs = `${source.hash}\0${JSON.stringify(config)}`
  const known = answers.get(appRoot)
  if (known?.inputs === inputs) return known.entry
  const entry = await lookup(appRoot)
  answers.set(appRoot, { inputs, entry })
  return entry
}

async function lookup(appRoot: string): Promise<ExpoNativeEntry | null> {
  const app = await expoNativeInputs(appRoot)
  if (!app) return null
  const url = expoNativeEntryUrl(nativeEntryKey(app.inputs), 'metadata.json')
  let pending = published.get(url)
  if (!pending) {
    pending = fetch(url)
      .then(async (response) =>
        response.ok ? readExpoNativeEntry(await response.json()) : null,
      )
      .catch(() => null)
    published.set(url, pending)
  }
  const entry = await pending
  if (!entry) return null
  const digests = await expoNativePackageDigests(app.packages)
  return isDeepStrictEqual(digests, entry.packages) ? entry : null
}

/**
 * the published native build for an app, or null when the app is not a
 * standard one, its packages' sources differ from the entry's, or our builder
 * has not published its key. a network failure is a miss: the local route that
 * follows reports its own failures.
 */
export function prebuiltExpoNative(
  appRoot: string,
  iosTarget: string | undefined,
): Promise<ExpoNativeEntry | null> {
  if (iosTarget !== undefined) return Promise.resolve(null)
  const root = fs.realpathSync(appRoot)
  let pending = lookups.get(root)
  if (!pending) {
    pending = answer(root).finally(() => lookups.delete(root))
    lookups.set(root, pending)
  }
  return pending
}

/** the app target prebuild alone writes, which a hit reads the app's own values from. */
export async function prebuiltAppTarget(
  appRoot: string,
  signal?: AbortSignal,
  dependencies: 'lockfile' | 'installed' = 'lockfile',
): Promise<XcodeAppTarget> {
  const prepared = await prepareExpoNativeProject(
    fs.realpathSync(appRoot),
    signal,
    dependencies,
  )
  const ios = path.join(prepared.app, 'ios')
  const projects = fs.readdirSync(ios).filter((name) => name.endsWith('.xcodeproj'))
  if (projects.length !== 1) throw new Error(`expected one Xcode project in ${ios}`)
  return readXcodeAppTarget(path.join(ios, projects[0]!), undefined, 'Debug', {
    requireSources: false,
  })
}

export function isManagedExpoApp(appRoot: string): boolean {
  return (
    !findXcodeProject(path.join(appRoot, 'ios')) &&
    declaresNativeDependency(
      JSON.parse(fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8')),
      'expo',
    )
  )
}

/** a managed app's Info.plist and entitlements exist only once prebuild runs its config plugins. */
export async function managedExpoNativeAppIdentity(
  appRoot: string,
  iosTarget?: string,
): Promise<NativeAppIdentity | null> {
  // the launch cache checks the workspace, including installed dependencies.
  const entry = iosTarget === undefined ? await lookup(appRoot) : null
  return readNativeAppIdentityFromXcodeTarget(
    await prebuiltAppTarget(appRoot, undefined, entry ? 'installed' : 'lockfile'),
  )
}

/** the Expo Swift result an entry serves an app, with its own root id, identity and Info.plist. */
export function servedExpoSwift(
  appRoot: string,
  entry: ExpoNativeEntry,
  app: XcodeAppTarget,
): ExpoSwiftCompilationResult | null {
  if (!entry.expoSwift) return null
  const rootId = `${createHash('sha256').update(fs.realpathSync(appRoot)).digest('hex')}/Expo`
  if (app.infoPlist === null) throw new Error('the prebuilt app target has no Info.plist')
  // pod install writes values such as RCTNewArchEnabled into the plist after
  // prebuild. the compile reads identity from that plist, so the hit must too.
  const installed = installedInfoPlist(app.infoPlist, entry.infoPlist)
  const infoPlist = Buffer.from(installed).toString('base64')
  return {
    ...entry.expoSwift,
    ...(entry.identity
      ? {
          nativeAppIdentity: readNativeAppIdentityFromXcodeTarget({
            ...app,
            infoPlist: installed,
          }),
        }
      : {}),
    modules: entry.expoSwift.modules.map((module) => ({
      ...module,
      rootId,
      bundleFiles: { 'Info.plist': infoPlist, ...module.bundleFiles },
    })),
  }
}

export async function prebuiltExpoSwiftResult(
  appRoot: string,
  entry: ExpoNativeEntry,
  signal?: AbortSignal,
): Promise<ExpoSwiftCompilationResult | null> {
  if (!entry.expoSwift) return null
  // an entry that links nothing and carries no identity needs nothing from the app
  if (entry.expoSwift.modules.length === 0 && !entry.identity) return entry.expoSwift
  return servedExpoSwift(
    appRoot,
    entry,
    await prebuiltAppTarget(appRoot, signal, 'installed'),
  )
}
