import groovy.json.JsonSlurper

plugins {
  id 'com.android.library'
  id 'expo-module-gradle-plugin'
}

def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

group = 'host.exp.exponent'
version = '56.0.5'

android {
  if (rootProject.hasProperty("ndkPath")) {
    ndkPath rootProject.ext.ndkPath
  }
  if (rootProject.hasProperty("ndkVersion")) {
    ndkVersion rootProject.ext.ndkVersion
  }

  namespace "expo.modules.gl"
  defaultConfig {
    versionCode 31
    versionName "56.0.5"

    externalNativeBuild {
      cmake {
        abiFilters (*reactNativeArchitectures())
        arguments "-DANDROID_STL=c++_shared",
          "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
      }
    }
  }

  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
    }
  }

  buildFeatures {
    prefab true
  }

  packagingOptions {
    // Gradle will add cmake target dependencies into packaging.
    excludes += [
        "**/libc++_shared.so",
        "**/libjsi.so",
    ]
  }

  configurations {
    extractHeaders
    extractJNI
  }
}

dependencies {
  compileOnly 'com.facebook.soloader:soloader:0.8.2'
  compileOnly 'com.facebook.react:react-android'
}

// Generates minimal stub PCH files from an empty header so the IDE's C++ engine
// doesn't fail during sync. Near-instant unlike the full ExpoHeader.pch.
// The actual build regenerates proper PCH files via ninja.
def cxxDir = project.file(".cxx")
def generateStubPCHTask = tasks.register("generateStubPCH") {
  dependsOn("configureCMakeDebug")

  doLast {
    if (!cxxDir.exists()) {
      return
    }

    cxxDir.eachFileRecurse { file ->
      if (file.name != "compile_commands.json") {
        return
      }

      new JsonSlurper().parseText(file.text).each { entry ->
        if (!entry.file.endsWith("cmake_pch.hxx.cxx")) {
          return
        }

        def pchFile = new File(entry.file.substring(0, entry.file.length() - ".cxx".length()) + ".pch")

        if (!pchFile.exists() || pchFile.length() == 0) {
          def stubHeader = new File(entry.directory, "stub_pch.hxx")
          stubHeader.text = ""

          def cmd = entry.command
            // Replace the forced-include path: `-Xclang -include -Xclang <path>/cmake_pch.hxx`
            .replaceAll(/-Xclang -include -Xclang [^\s]+cmake_pch\.hxx(?=\s)/, "-Xclang -include -Xclang ${stubHeader.absolutePath}")
            // Replace the source file operand: `<path>/cmake_pch.hxx.cxx`
            .replaceAll(/[^\s]+cmake_pch\.hxx\.cxx/, stubHeader.absolutePath)

          def process = new ProcessBuilder(cmd.split(" ").toList())
            .directory(new File(entry.directory))
            .redirectErrorStream(true)
            .start()
          if (process.waitFor() != 0) {
            throw new GradleException("Stub PCH generation failed: ${process.inputStream.text}")
          }
        }

        // Ensure PCH is older than source so ninja rebuilds the real one during build
        pchFile.setLastModified(new File(entry.file).lastModified() - 1)
      }
    }
  }
}

tasks.register("prepareKotlinBuildScriptModel") {
  dependsOn(generateStubPCHTask)
}
