import { execFile } from 'node:child_process'
import { randomBytes } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { promisify } from 'node:util'
import { PEACH_FORKED_SCRIPT_ENV } from './forked-script-contract'
import { isRecord } from './is-record'
import { kotlinHome } from './kotlin-toolchain'
import type {
  AndroidGradleDependency,
  AndroidGradleSourceRequest,
  AndroidGradleSources,
} from './androidGradleContract'

const run = promisify(execFile)
const modelQuery = `
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.gradle.api.artifacts.FileCollectionDependency
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.artifacts.result.ResolvedDependencyResult
import org.gradle.api.attributes.Category

def request = new JsonSlurper().parseText(new String(Base64.decoder.decode('__PEACH_REQUEST__'), 'UTF-8'))
def selectedVariants = [:]
gradle.beforeProject { project ->
    def directory = project.projectDir.canonicalPath
    if (project.rootProject.projectDir.canonicalPath != request.root || !request.projects.contains(directory)) return
    ['com.android.application', 'com.android.library'].each { plugin ->
        project.pluginManager.withPlugin(plugin) {
            def components = project.extensions.getByName('androidComponents')
            components.onVariants(components.selector().withName(request.variant)) { variant ->
                selectedVariants[directory] = variant
            }
        }
    }
}
gradle.projectsEvaluated {
    if (gradle.rootProject.projectDir.canonicalPath != request.root) return
    def selected = []
    request.projects.eachWithIndex { directory, index ->
        def matches = gradle.rootProject.allprojects.findAll { it.projectDir.canonicalPath == directory }
        if (matches.size() != 1) throw new GradleException('Expected one Android project for ' + directory)
        def project = matches[0]
        if (project.pluginManager.hasPlugin('org.jetbrains.kotlin.multiplatform')) {
            throw new GradleException('Kotlin multiplatform source selection is not supported: ' + project.path)
        }
        def library = project.pluginManager.hasPlugin('com.android.library')
        if (!library && !project.pluginManager.hasPlugin('com.android.application')) {
            throw new GradleException('Project has no Android application or library plugin: ' + project.path)
        }
        def variant = selectedVariants[directory]
        if (variant == null) throw new GradleException('Android variant ' + request.variant + ' is absent: ' + project.path)
        def generators = []
        if (project.pluginManager.hasPlugin('com.facebook.react')) {
            generators.add(project.tasks.named('generateCodegenArtifactsFromSchema'))
        }
        def kotlin = project.tasks.findByName('compile' + variant.name.capitalize() + 'Kotlin')
        def kotlinSources = kotlin == null ? project.files() : kotlin.sources
        def javaSources = project.tasks.named('compile' + variant.name.capitalize() + 'JavaWithJavac').get().source
        def query = project.tasks.register(request.task) {
            dependsOn(generators)
            dependsOn(kotlinSources.buildDependencies, javaSources.buildDependencies)
            doLast {
                def files = (kotlinSources.files + javaSources.files).unique()
                def unknown = files.find { !it.name.endsWith('.kt') && !it.name.endsWith('.java') }
                if (unknown != null) throw new GradleException('Unsupported Android source: ' + unknown)
                def dependencies = [variant.compileConfiguration, variant.runtimeConfiguration].collectMany { configuration ->
                    def modules = configuration.incoming.resolutionResult.rootComponent.get().dependencies.findAll { !it.constraint }.collectMany { dependency ->
                        if (!(dependency instanceof ResolvedDependencyResult)) throw new GradleException('Unresolved Android dependency: ' + dependency.requested, dependency.failure)
                        def category = dependency.resolvedVariant.attributes.getAttribute(Category.CATEGORY_ATTRIBUTE)?.name
                        if (category == Category.REGULAR_PLATFORM || category == Category.ENFORCED_PLATFORM) return []
                        def id = dependency.selected.id
                        if (id instanceof ModuleComponentIdentifier) return [[kind:'module', group:id.group, name:id.module, version:id.version]]
                        if (id instanceof ProjectComponentIdentifier) return [[kind:'project', name:id.displayName]]
                        throw new GradleException('Unsupported Android dependency component: ' + id.displayName)
                    }
                    def local = configuration.allDependencies.withType(FileCollectionDependency).collectMany { dependency ->
                        dependency.files.files.collect { [kind:'file', name:it.absolutePath] }
                    }
                    modules + local
                }.unique()
                new File(request.output, index.toString() + '.json').text = JsonOutput.toJson([
                    projectDir:project.projectDir.canonicalPath,
                    projectPath:project.path,
                    variant:variant.name,
                    applicationId:library ? null : variant.applicationId.get(),
                    namespace:variant.namespace.get(),
                    targetSdk:library ? null : variant.targetSdk.apiLevel,
                    kotlin:files.findAll { it.name.endsWith('.kt') }.collect { it.absolutePath }.sort(),
                    java:files.findAll { it.name.endsWith('.java') }.collect { it.absolutePath }.sort(),
                    dependencies:dependencies
                ])
            }
        }
        selected.add(query)
    }
    gradle.rootProject.tasks.register(request.task + 'All') { dependsOn(selected) }
}
`

export async function resolveAndroidGradleSources(
  request: AndroidGradleSourceRequest,
): Promise<AndroidGradleSources[]> {
  let { root } = request
  const { projects: projectDirs, variant } = request
  if (projectDirs.length === 0) return []
  if (!path.isAbsolute(root) || projectDirs.some((dir) => !path.isAbsolute(dir)))
    throw new Error('Android Gradle source selection requires absolute project paths')
  if (!variant) throw new Error('Android Gradle source selection requires a variant')
  root = fs.realpathSync(root)
  const projects = [...new Set(projectDirs.map((dir) => fs.realpathSync(dir)))]
  const parent = path.join(kotlinHome(), 'gradle-sources')
  fs.mkdirSync(parent, { recursive: true })
  const work = fs.mkdtempSync(path.join(parent, '.query-'))
  const task = `peachAndroidSources${randomBytes(8).toString('hex')}`
  const script = path.join(work, 'sources.gradle')
  const encoded = Buffer.from(
    JSON.stringify({ root, projects, variant, output: work, task }),
  ).toString('base64')
  fs.writeFileSync(script, modelQuery.replace('__PEACH_REQUEST__', encoded))
  try {
    await run(
      'bash',
      [
        path.join(root, 'gradlew'),
        '--init-script',
        script,
        `${task}All`,
        '--no-daemon',
        '--no-configuration-cache',
        '--no-configure-on-demand',
        '--max-workers=1',
        '--console=plain',
      ],
      {
        cwd: root,
        timeout: 300_000,
        maxBuffer: 8 * 1024 * 1024,
        env: { ...process.env, [PEACH_FORKED_SCRIPT_ENV]: '1' },
      },
    )
    return projects.map((projectDir, index): AndroidGradleSources => {
      const value: unknown = JSON.parse(
        fs.readFileSync(path.join(work, `${index}.json`), 'utf8'),
      )
      if (
        !isRecord(value) ||
        value.projectDir !== projectDir ||
        value.variant !== variant ||
        typeof value.projectPath !== 'string' ||
        (value.applicationId !== null && typeof value.applicationId !== 'string') ||
        typeof value.namespace !== 'string' ||
        !value.namespace ||
        (value.targetSdk !== null &&
          (typeof value.targetSdk !== 'number' ||
            !Number.isInteger(value.targetSdk) ||
            value.targetSdk <= 0))
      )
        throw new Error('Gradle printed an invalid Android project source model')
      const sources = (field: 'kotlin' | 'java'): string[] => {
        const list = value[field]
        if (
          !Array.isArray(list) ||
          !list.every((file) => typeof file === 'string' && path.isAbsolute(file))
        )
          throw new Error(`Gradle printed invalid Android ${field} source paths`)
        return list.map(String)
      }
      if (!Array.isArray(value.dependencies))
        throw new Error('Gradle printed invalid Android dependencies')
      const dependencies = value.dependencies.map(
        (entry: unknown): AndroidGradleDependency => {
          if (isRecord(entry) && typeof entry.name === 'string' && entry.name) {
            if (
              entry.kind === 'module' &&
              typeof entry.group === 'string' &&
              entry.group &&
              typeof entry.version === 'string' &&
              entry.version
            )
              return {
                kind: entry.kind,
                group: entry.group,
                name: entry.name,
                version: entry.version,
              }
            if (entry.kind === 'project' || entry.kind === 'file')
              return { kind: entry.kind, name: entry.name }
          }
          throw new Error('Gradle printed an invalid Android dependency')
        },
      )
      return {
        projectDir,
        projectPath: value.projectPath,
        variant,
        applicationId: value.applicationId,
        namespace: value.namespace,
        targetSdk: value.targetSdk,
        kotlin: sources('kotlin'),
        java: sources('java'),
        dependencies,
      }
    })
  } finally {
    fs.rmSync(work, { recursive: true, force: true })
  }
}
