import groovy.json.JsonSlurper
import org.apache.tools.ant.filters.ReplaceTokens
import java.nio.file.Paths

static def findNodeModules(baseDir) {
  def basePath = baseDir.toPath().normalize()
  // Node's module resolution algorithm searches up to the root directory,
  // after which the base path will be null
  while (basePath) {
    def nodeModulesPath = Paths.get(basePath.toString(), "node_modules")
    def reactNativePath = Paths.get(nodeModulesPath.toString(), "react-native")
    if (nodeModulesPath.toFile().exists() && reactNativePath.toFile().exists()) {
      return nodeModulesPath.toString()
    }
    basePath = basePath.getParent()
  }
  throw new GradleException("react-native-config-jsi: Failed to find node_modules/ path!")
}

def nodeModules = findNodeModules(projectDir)
logger.warn("react-native-config-jsi: node_modules/ found at: ${nodeModules}")


buildscript {
  ext.getExtOrDefault = {name ->
    return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['ConfigJsi_' + name]
  }

  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:8.7.2"
    // noinspection DifferentKotlinGradleVersion
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
  }
}

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

def isNewArchitectureEnabled() {
  return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
}

apply plugin: "com.android.library"
apply plugin: "kotlin-android"

if (isNewArchitectureEnabled()) {
  apply plugin: "com.facebook.react"
}

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["ConfigJsi_" + name]).toInteger()
}

def supportsNamespace() {
  def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
  def major = parsed[0].toInteger()
  def minor = parsed[1].toInteger()

  // Namespace support was added in 7.3.0
  return (major == 7 && minor >= 3) || major >= 8
}

android {
  if (supportsNamespace()) {
    namespace "com.configjsi"

    sourceSets {
      main {
        manifest.srcFile "src/main/AndroidManifestNew.xml"
      }
    }
  }

  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

    externalNativeBuild {
      cmake {
        cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all"
        abiFilters (*reactNativeArchitectures())
        arguments "-DANDROID_STL=c++_shared",
                  "-DNODE_MODULES_DIR=${nodeModules}"
      }
    }
  }

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

  buildFeatures {
    buildConfig true
    prefab true
  }

  packagingOptions {
    excludes = [
            "**/libjsi.so",
             "**/libreactnativejni.so",
            "**/libreact_nativemodule_core.so",
            "**/libturbomodulejsijni.so",
            "**/libc++_shared.so",
            "**/libfbjni.so",
            "**/libreactnative.so",
    ]
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  sourceSets {
    main {
      if (isNewArchitectureEnabled()) {
          java.srcDirs += [
            "generated/java",
            "generated/jni"
          ]
      }
    }
  }
}

repositories {
  mavenCentral()
  google()
}

def kotlin_version = getExtOrDefault("kotlinVersion")

dependencies {
  implementation "com.facebook.react:react-android"
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

if (isNewArchitectureEnabled()) {
  react {
    jsRootDir = file("../src/")
    libraryName = "ConfigJsi"
    codegenJavaPackageName = "com.configjsi"
  }
}

apply from: "dotenv.gradle"