buildscript {
  // Buildscript is evaluated before everything else so we can't use getExtOrDefault
  def kotlin_version = rootProject.ext.has("kotlinVersion") ? rootProject.ext.get("kotlinVersion") : project.properties["RNNitroSQLite_kotlinVersion"]

  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.2"
    // noinspection DifferentKotlinGradleVersion
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

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"
}

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

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

def safeAppExtGet(prop, fallback) {
  def appProject = rootProject.allprojects.find { it.plugins.hasPlugin('com.android.application') }
  appProject?.ext?.has(prop) ? appProject.ext.get(prop) : fallback
}

def resolveBuildType() {
  Gradle gradle = getGradle()
  String tskReqStr = gradle.getStartParameter().getTaskRequests()['args'].toString()
  return tskReqStr.contains('Release') ? 'release' : 'debug'
}

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
}

def resolveReactNativeDirectory() {
  def reactNativeLocation = safeAppExtGet("REACT_NATIVE_NODE_MODULES_DIR", null)
  if (reactNativeLocation != null) {
    return file(reactNativeLocation)
  }

  // Fallback to node resolver for custom directory structures like monorepos.
  def reactNativePackage = file(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim())
  if (reactNativePackage.exists()) {
    return reactNativePackage.parentFile
  }

  throw new GradleException("[react-native-nitro-sqlite] Unable to resolve react-native location in node_modules. Your app should define `REACT_NATIVE_NODE_MODULES_DIR` extension property in `app/build.gradle` with a path to react-native in node_modules.")
}

def reactNativeRootDir = resolveReactNativeDirectory()
def reactProperties = new Properties()
file("$reactNativeRootDir/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }

def REACT_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME")
def REACT_NATIVE_MINOR_VERSION = REACT_NATIVE_VERSION.startsWith("0.0.0-") ? 1000 : REACT_NATIVE_VERSION.split("\\.")[1].toInteger()

def SQLITE_FLAGS = rootProject.properties['nitroSqliteFlags']

// Opt-in: resolve the companion's cpp dir so CMake compiles its sqlite-vec into this library.
def NITRO_SQLITE_VEC_ENABLED = (rootProject.findProperty('nitroSqliteVec') ?: 'false').toString() == 'true'
def NITRO_SQLITE_VEC_CPP_DIR = ''
if (NITRO_SQLITE_VEC_ENABLED) {
  try {
    def vecPkgJson = ["node", "--print", "require.resolve('react-native-nitro-sqlite-vec/package.json')"].execute(null, rootDir).text.trim()
    NITRO_SQLITE_VEC_CPP_DIR = new File(new File(vecPkgJson).parentFile, "cpp").absolutePath
  } catch (Exception e) {
    throw new GradleException("[react-native-nitro-sqlite] nitroSqliteVec=true but 'react-native-nitro-sqlite-vec' could not be resolved. Install it in your app (e.g. `bun add react-native-nitro-sqlite-vec`).")
  }
}

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

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

apply from: '../nitrogen/generated/android/RNNitroSQLite+autolinking.gradle'

android {
  if (supportsNamespace()) {
    namespace "com.margelo.rnnitrosqlite"

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

  ndkVersion getExtOrDefault("ndkVersion")
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")

    buildConfigField "int", "REACT_NATIVE_MINOR_VERSION", REACT_NATIVE_MINOR_VERSION.toString()
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

    externalNativeBuild {
      cmake {
        arguments "-DANDROID_STL=c++_shared",
          "-DANDROID_TOOLCHAIN=clang",
          "-DREACT_NATIVE_MINOR_VERSION=${REACT_NATIVE_MINOR_VERSION}",
          "-DSQLITE_FLAGS='${SQLITE_FLAGS ? SQLITE_FLAGS : ''}'",
          "-DNITRO_SQLITE_VEC=${NITRO_SQLITE_VEC_ENABLED ? 'ON' : 'OFF'}",
          "-DNITRO_SQLITE_VEC_CPP_DIR=${NITRO_SQLITE_VEC_CPP_DIR}",
          "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
        abiFilters (*reactNativeArchitectures())
      }
    }
  }

  externalNativeBuild {
    cmake {
      path "CMakeLists.txt"
      version = System.getenv("CMAKE_VERSION") ?: "3.22.1"
    }
  }

  buildFeatures {
    buildConfig true
    prefab true
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
  }

  sourceSets {
    main {
      java.srcDirs += [
        "src/main/kotlin"
      ]

      if (isNewArchitectureEnabled()) {
        java.srcDirs += ["src/newarch"]
      } else {
        java.srcDirs += ["src/oldarch"]
      }
    }
  }

  packagingOptions {
    doNotStrip resolveBuildType() == 'debug' ? "**/**/*.so" : ''
    excludes = [
      "META-INF",
      "META-INF/**",
      "**/libreactnative.so",
      "**/libreact_nativemodule_core.so",
      "**/libc++_shared.so",
      "**/libfbjni.so",
      "**/libjsi.so",
      "**/libhermes.so",
    ]
  }
}

repositories {
  mavenCentral()
  google()
}

def kotlin_version = getExtOrDefault("kotlinVersion")

dependencies {
  // For < 0.71, this will be from the local maven repo
  // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
  //noinspection GradleDynamicVersion
  implementation "com.facebook.react:react-native:+"
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

  // Add a dependency on NitroModules
  implementation project(":react-native-nitro-modules")
}

if (isNewArchitectureEnabled()) {
  react {
    jsRootDir = file("../src/")
    libraryName = "RNNitroSQLite"
  }
}
