import { createHash } from 'node:crypto'
import fs from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
import { materialSymbolFontNames } from '../src/material-symbol-fonts'

// these assets are selected by @react-navigation/native's copyMaterialFonts
// gradle task. they never enter metro's module graph.
export function materialSymbolFontPaths(appDir: string): string[] {
  const appRequire = createRequire(path.join(appDir, 'package.json'))
  let nativeManifest: string
  try {
    nativeManifest = appRequire.resolve('@react-navigation/native/package.json')
  } catch {
    return []
  }
  const nativePackage: unknown = JSON.parse(fs.readFileSync(nativeManifest, 'utf8'))
  const dependencies =
    nativePackage && typeof nativePackage === 'object'
      ? Reflect.get(nativePackage, 'dependencies')
      : null
  if (
    !dependencies ||
    typeof dependencies !== 'object' ||
    !Reflect.has(dependencies, '@react-navigation/material-symbols')
  )
    return []
  const nativeRequire = createRequire(nativeManifest)
  const symbolsDir = path.dirname(
    nativeRequire.resolve('@react-navigation/material-symbols/package.json'),
  )
  const fontsDir = path.join(symbolsDir, 'assets/fonts')
  const available = fs.existsSync(fontsDir)
    ? fs
        .readdirSync(fontsDir)
        .filter((name) => name.startsWith('MaterialSymbols') && name.endsWith('.ttf'))
    : []
  const manifest: unknown = JSON.parse(
    fs.readFileSync(path.join(appDir, 'package.json'), 'utf8'),
  )
  return materialSymbolFontNames(manifest, available, symbolsDir).map((name) =>
    path.join(fontsDir, name),
  )
}

// the native task hashes selected fonts and the two symbol maps in filename order.
export function materialSymbolFontAssets(
  fontPaths: readonly string[],
): { hash: string; codepointsPath: string; mirroredPath: string } | undefined {
  const selected = fontPaths.filter((fontPath) =>
    /^MaterialSymbols(?:Outlined|Rounded|Sharp)_\d+(?:_Filled)?\.ttf$/.test(
      path.basename(fontPath),
    ),
  )
  if (!selected.length) return undefined
  const directory = path.dirname(selected[0]!)
  const codepointsFile = path.join(directory, 'MaterialSymbols.codepoints')
  const mirroredFile = path.join(directory, 'MaterialSymbols.mirrored')
  const digest = createHash('md5')
  for (const asset of [...selected, codepointsFile, mirroredFile].sort((a, b) =>
    path.basename(a) < path.basename(b)
      ? -1
      : path.basename(a) > path.basename(b)
        ? 1
        : 0,
  )) {
    digest.update(fs.readFileSync(asset))
  }
  return {
    hash: digest.digest('hex').slice(0, 8),
    codepointsPath: codepointsFile,
    mirroredPath: mirroredFile,
  }
}
