// use each native autolinker for its module families and platform exclusions.
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 { readAndroidAutolinkedPackages } from './androidAutolinkingContract'
import { PEACH_FORKED_SCRIPT_ENV } from './forked-script-contract'
import { isRecord } from './is-record'
import { reactNativeAutolinkingConfig } from './react-native-autolinking'
import type { AndroidAutolinkedDependency } from './androidAutolinkingContract'

const run = promisify(execFile)

const resolving = new Map<string, Promise<readonly Record<string, unknown>[]>>()

// only an overlapping resolution pass is shared. later builds must observe
// changed dependencies, module configuration and autolinking exclusions.
export async function resolveExpoAndroidAutolinking(
  appRoot: string,
): Promise<readonly Record<string, unknown>[]> {
  const root = fs.realpathSync(appRoot)
  const existing = resolving.get(root)
  if (existing) return existing
  const pending = resolveAndroidModules(root)
  resolving.set(root, pending)
  try {
    return await pending
  } finally {
    if (resolving.get(root) === pending) resolving.delete(root)
  }
}

async function resolveAndroidModules(
  appRoot: string,
): Promise<readonly Record<string, unknown>[]> {
  let autolinker: string
  try {
    autolinker = createRequire(path.join(appRoot, 'package.json')).resolve(
      'expo-modules-autolinking/package.json',
    )
  } catch (error) {
    if (isRecord(error) && error.code === 'MODULE_NOT_FOUND') return []
    throw error
  }
  const { stdout } = await run(
    process.execPath,
    [
      path.join(path.dirname(autolinker), 'bin/expo-modules-autolinking.js'),
      'resolve',
      '--platform',
      'android',
      '--project-root',
      appRoot,
      '--json',
    ],
    {
      timeout: 30_000,
      maxBuffer: 8 * 1024 * 1024,
      env: { ...process.env, [PEACH_FORKED_SCRIPT_ENV]: '1' },
      cwd: appRoot,
    },
  )
  const resolved: unknown = JSON.parse(stdout)
  if (!isRecord(resolved) || !Array.isArray(resolved.modules))
    throw new Error('invalid Expo Android autolinking result')
  if (!resolved.modules.every(isRecord))
    throw new Error('invalid Expo Android autolinking entry')
  return resolved.modules
}

export async function collectAndroidAutolinkedPackages(
  appRoot: string,
): Promise<string[]> {
  const [modules, dependencies] = await Promise.all([
    resolveExpoAndroidAutolinking(appRoot),
    resolveReactNativeAndroidAutolinking(appRoot),
  ])
  return readAndroidAutolinkedPackages([
    ...modules.map((entry) => entry.packageName),
    ...dependencies.map((entry) => entry.name),
  ])
}

export async function resolveReactNativeAndroidAutolinking(
  appRoot: string,
): Promise<AndroidAutolinkedDependency[]> {
  const config = await reactNativeAutolinkingConfig(appRoot, 'android')
  if (!isRecord(config) || !isRecord(config.dependencies))
    throw new Error(`${appRoot}: React Native autolinking config has no dependencies`)
  const linked: AndroidAutolinkedDependency[] = []
  for (const [name, dependency] of Object.entries(config.dependencies)) {
    if (!isRecord(dependency) || !isRecord(dependency.platforms))
      throw new Error(
        `${appRoot}: React Native autolinking dependency ${name} is malformed`,
      )
    const android = dependency.platforms.android
    if (android == null) continue
    if (!isRecord(android) || typeof dependency.root !== 'string')
      throw new Error(
        `${appRoot}: React Native autolinking dependency ${name} has no Android project`,
      )
    const string = (field: string): string | null => {
      const value = android[field]
      if (value == null || typeof value === 'string') return value ?? null
      throw new Error(`${appRoot}: Android dependency ${name} has invalid ${field}`)
    }
    linked.push({
      name,
      root: dependency.root,
      sourceDir: string('sourceDir'),
      packageImportPath: string('packageImportPath'),
      packageInstance: string('packageInstance'),
    })
  }
  return linked
}
