import com.android.Version
import org.apache.tools.ant.taskdefs.condition.Os

buildscript {
  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:7.2.2"
  }
}

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

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

def isFFmpegDisabled() {
  return rootProject.hasProperty("disableAudioapiFFmpeg") && rootProject.getProperty("disableAudioapiFFmpeg") == "true"
}

apply plugin: "com.android.library"
apply plugin: 'org.jetbrains.kotlin.android'

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

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

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

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

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 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(
      "[AudioAPI] Unable to resolve react-native location in node_modules. You should project extension property (in `app/build.gradle`) `REACT_NATIVE_NODE_MODULES_DIR` with path to react-native."
  )
}

def resolveReactNativeWorkletsDirectory() {
  def rnWorklets = rootProject.subprojects.find { it.name == 'react-native-worklets' }
  if (rnWorklets != null) {
    return rnWorklets.projectDir
  }

  return null;
}

def validateWorkletsVersion() {
  def validationScript = file("${projectDir}/../scripts/validate-worklets-version.js")
  if (!validationScript.exists()) {
    logger.error("[AudioAPI] Worklets validation script not found at ${validationScript.absolutePath}")
    return false
  }

  try {
    def process = ["node", validationScript.absolutePath].execute()
    process.waitForProcessOutput(System.out, System.err)
    def exitCode = process.exitValue()

    if (exitCode == 0) {
      return true
    } else {
      logger.warn("[AudioAPI] Worklets version validation failed")
      return false
    }
  } catch (Exception e) {
    logger.error("[AudioAPI] Failed to validate worklets version: ${e.message}")
    return false
  }
}

def toPlatformFileString(String path) {
  if (Os.isFamily(Os.FAMILY_WINDOWS)) {
      path = path.replace(File.separatorChar, '/' as char)
  }
  return path
}

static def supportsNamespace() {
  def parsed = 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 reactNativeRootDir = resolveReactNativeDirectory()
def reactNativeWorkletsRootDir = resolveReactNativeWorkletsDirectory()
def isWorkletsAvailable = reactNativeWorkletsRootDir != null && validateWorkletsVersion()

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 IS_NEW_ARCHITECTURE_ENABLED = isNewArchitectureEnabled()
def IS_RN_AUDIO_API_FFMPEG_DISABLED = isFFmpegDisabled()

android {
  sourceSets {
      main {
          jniLibs.srcDirs = ['src/main/jniLibs']
      }
  }
  if (supportsNamespace()) {
    namespace "com.swmansion.audioapi"

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

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

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    consumerProguardFiles("proguard-rules.pro")

    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    buildConfigField "boolean", "RN_AUDIO_API_ENABLE_WORKLETS", "${isWorkletsAvailable}"
    buildConfigField "boolean", "RN_AUDIO_API_FFMPEG_DISABLED", isFFmpegDisabled().toString()

    externalNativeBuild {
      cmake {
        abiFilters (*reactNativeArchitectures())

        def cmakeArgs = [
          "-DANDROID_STL=c++_shared",
          "-DREACT_NATIVE_MINOR_VERSION=${REACT_NATIVE_MINOR_VERSION}",
          "-DANDROID_TOOLCHAIN=clang",
          "-DREACT_NATIVE_DIR=${toPlatformFileString(reactNativeRootDir.path)}",
          "-DRN_AUDIO_API_WORKLETS_ENABLED=${isWorkletsAvailable}",
          "-DIS_NEW_ARCHITECTURE_ENABLED=${IS_NEW_ARCHITECTURE_ENABLED}",
          "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
          "-DRN_AUDIO_API_FFMPEG_DISABLED=${IS_RN_AUDIO_API_FFMPEG_DISABLED}"
        ]

        if (isWorkletsAvailable) {
          cmakeArgs << "-DREACT_NATIVE_WORKLETS_DIR=${toPlatformFileString(reactNativeWorkletsRootDir.path)}"
        }
        arguments = cmakeArgs
      }
    }
  }

  packagingOptions {
    jniLibs {
      useLegacyPackaging = false  // enables 16KB alignment
    }
    excludes = [
      "META-INF",
      "META-INF/**",
      "**/libc++_shared.so",
      "**/libfbjni.so",
      "**/libjsi.so",
      "**/libfolly_json.so",
      "**/libfolly_runtime.so",
      "**/libglog.so",
      "**/libhermes.so",
      "**/libhermesvm.so",
      "**/libhermes-executor-debug.so",
      "**/libhermes_executor.so",
      "**/libhermestooling.so",
      "**/libreactnativejni.so",
      "**/libturbomodulejsijni.so",
      "**/libreactnative.so",
      "**/libreact_nativemodule_core.so",
      "**/libreact_render*.so",
      "**/librrc_root.so",
      "**/libjscexecutor.so",
      "**/libv8executor.so",
      "**/libreanimated.so"
    ]
  }

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

  buildFeatures {
    buildConfig true
    prefab true
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17

    packagingOptions {
      doNotStrip resolveBuildType() == 'debug' ? "**/**/*.so" : ''

      excludes = [
        "**/libjsi.so",
        "**/libfolly_runtime.so",
        "**/libreactnativejni.so",
        "**/libreactnative.so",
      ]
    }
  }

  sourceSets {
    main {
      if (isNewArchitectureEnabled()) {
          java.srcDirs += [
            // This is needed to build Kotlin project with NewArch enabled
            "${project.buildDir}/generated/source/codegen/java"
          ]
      } else {
        java.srcDirs += ["src/oldarch"]
      }
    }
  }
  kotlinOptions {
    jvmTarget = '17'
  }
}

repositories {
  mavenCentral()
  google()
}


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 'androidx.core:core-ktx:1.13.1'
  implementation 'com.facebook.fbjni:fbjni:0.6.0'
  implementation 'com.google.oboe:oboe:1.9.3'
  implementation 'androidx.media:media:1.7.0'

  if (isWorkletsAvailable) {
    implementation(rootProject.subprojects.find { it.name == 'react-native-worklets' })
  }
}

if (isWorkletsAvailable) {
  // Ensure worklets is built before react-native-audio-api
  def rnWorkletsProject = rootProject.subprojects.find { it.name == 'react-native-worklets' }
  evaluationDependsOn(rnWorkletsProject.path)

  afterEvaluate {
      tasks.getByName("buildCMakeDebug").dependsOn(rnWorkletsProject.tasks.getByName("mergeDebugNativeLibs"))
      tasks.getByName("buildCMakeRelWithDebInfo").dependsOn(rnWorkletsProject.tasks.getByName("mergeReleaseNativeLibs"))
  }
}


def assertMinimalReactNativeVersion = task assertMinimalReactNativeVersionTask {
    // If you change the minimal React Native version remember to update Compatibility Table in docs
    def minimalReactNativeVersion = 76
    onlyIf { REACT_NATIVE_MINOR_VERSION < minimalReactNativeVersion }
    doFirst {
        throw new GradleException("[AudioAPI] Unsupported React Native version. Please use $minimalReactNativeVersion. or newer.")
    }
}

task downloadPrebuiltBinaries(type: Exec) {
  commandLine 'chmod', '+x', '../scripts/download-prebuilt-binaries.sh'
  commandLine 'bash', '../scripts/download-prebuilt-binaries.sh'
  args 'android', isFFmpegDisabled() ? 'skipffmpeg' : ''
}

// Make preBuild depend on the download task
tasks.preBuild {
    dependsOn assertMinimalReactNativeVersion
    dependsOn downloadPrebuiltBinaries
}

task cleanCmakeCache() {
    tasks.getByName("clean").dependsOn(cleanCmakeCache)
    doFirst {
        delete "${projectDir}/.cxx"
    }
}
