import { execFile } from 'node:child_process'
import fs from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
import { promisify } from 'node:util'
import { PEACH_FORKED_SCRIPT_ENV } from './forked-script-contract'

// the autolinker's command line changed across Expo releases: before 1.8.0 it
// takes the project from its working directory, before 1.10.3 the Apple
// platform is named `ios`.
export function autolinkerAppleFlags(autolinkerManifest: string, appRoot: string) {
  const manifest: unknown = JSON.parse(fs.readFileSync(autolinkerManifest, 'utf8'))
  const version =
    manifest && typeof manifest === 'object' && Reflect.get(manifest, 'version')
  const parts =
    typeof version === 'string'
      ? version.split('.').map((part) => Number.parseInt(part, 10))
      : []
  const [major, minor, patch] = parts
  if (!Number.isInteger(major) || !Number.isInteger(minor) || !Number.isInteger(patch))
    throw new Error(
      `unreadable expo-modules-autolinking version in ${autolinkerManifest}`,
    )
  const atLeast = (m: number, n: number, p: number) =>
    major !== m ? major > m : minor !== n ? minor > n : patch >= p
  if (atLeast(1, 10, 3)) return ['--platform', 'apple', '--project-root', appRoot]
  if (atLeast(1, 8, 0)) return ['--platform', 'ios', '--project-root', appRoot]
  return ['--platform', 'ios']
}

const run = promisify(execFile)

async function autolinkerResults(appRoot: string) {
  const appRequire = createRequire(path.join(appRoot, 'package.json'))
  let manifest: string
  try {
    manifest = appRequire.resolve('expo-modules-autolinking/package.json')
  } catch (error) {
    if (Reflect.get(Object(error), 'code') === 'MODULE_NOT_FOUND') return null
    throw error
  }
  const cli = path.join(path.dirname(manifest), 'bin/expo-modules-autolinking.js')
  const flags = autolinkerAppleFlags(manifest, appRoot)
  const [search, resolve] = await Promise.all(
    ['search', 'resolve'].map(async (command) =>
      JSON.parse(
        (
          await run('node', [cli, command, ...flags, '--json'], {
            cwd: appRoot,
            timeout: 120_000,
            maxBuffer: 8 * 1024 * 1024,
            env: { ...process.env, [PEACH_FORKED_SCRIPT_ENV]: '1' },
          })
        ).stdout,
      ),
    ),
  )
  const modules: AutolinkedModule[] = resolve.modules
  return { search, modules }
}

interface AutolinkedModule {
  packageName: string
  swiftModuleNames?: string[]
  pods: { podName: string; podspecDir: string }[]
}

/** the Apple pods of every Expo module the app's autolinker selects, which the
 *  React Native autolinker leaves out; an app without the autolinker has none. */
export async function expoAutolinkedPods(
  appRoot: string,
): Promise<{ name: string; root: string; podspecPath: string }[]> {
  const linked = await autolinkerResults(appRoot)
  return (linked?.modules ?? []).flatMap((module) =>
    module.pods.map((pod) => ({
      name: module.packageName,
      root: linked!.search[module.packageName].path,
      podspecPath: path.join(pod.podspecDir, `${pod.podName}.podspec`),
    })),
  )
}

/** each installed Expo module package the app's autolinker selects, with the Swift modules it builds. */
export async function expoAutolinkedPackages(
  appRoot: string,
): Promise<{ name: string; root: string; swiftModuleNames: string[] }[]> {
  const linked = await autolinkerResults(appRoot)
  return (linked?.modules ?? []).map((module) => ({
    name: module.packageName,
    root: fs.realpathSync(linked!.search[module.packageName].path),
    swiftModuleNames: module.swiftModuleNames ?? [],
  }))
}
