import groovy.json.JsonSlurper

buildscript {
  repositories {
    google()
    mavenCentral()
  }

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

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

apply plugin: "com.android.library"
apply from: "https://ve-vos.volccdn.com/script/vevos-repo-base.gradle"

if (isNewArchitectureEnabled()) {
  logger.info("react-native-veplayer: Using new architecture")
  apply plugin: "com.facebook.react"
}

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

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["Ve_" + 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
}

def getLicenseType() {
  try {
    def packageJson = file("../../../../package.json")
    def parsedJson = new JsonSlurper().parseText(packageJson.text)
    return parsedJson.TTVideoEngine.licenseType
  } catch (e) {
    return "premium"
  }
}

// Check if using global AppLog
def useGlobalAppLog() {
  // Check if the root project defines the USE_GLOBAL_RANGERS_APP_LOG property
  if (rootProject.hasProperty("USE_GLOBAL_RANGERS_APP_LOG")) {
    def useGlobalAppLogValue = rootProject.getProperty("USE_GLOBAL_RANGERS_APP_LOG")
    logger.info("useGlobalAppLogValue:", useGlobalAppLogValue)
    // Convert string to boolean
    if (useGlobalAppLogValue instanceof Boolean) {
      return useGlobalAppLogValue
    } else if (useGlobalAppLogValue instanceof String) {
      return useGlobalAppLogValue.toLowerCase() == "true"
    }
  }
  // Default to not using global AppLog
  return false
}

android {
  if (supportsNamespace()) {
    namespace "com.volcengine.reactnative.veplayer"

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

  // Ensure source sets include New/Old Architecture java sources
  sourceSets {
    main {
      java.srcDirs = ["src/main/java"]
      if (isNewArchitectureEnabled()) {
        java.srcDirs += ["src/newarch"]
      } else {
        java.srcDirs += ["src/oldarch"]
      }
    }
  }

  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

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

    consumerProguardFiles 'proguard-rules.pro' 

    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled() ? "true" : "false"
  }

  buildTypes {
    release {
      minifyEnabled false
    }
  }

  lintOptions {
    disable "GradleCompatible"
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

repositories {
  mavenCentral()
  google()
  maven {
    url "https://artifact.bytedance.com/repository/Volcengine/" // volc public maven repo
  }
}

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:+"
  def license_type = getLicenseType()
  logger.info("ttsdk-player license_type:", license_type)
  
  // Version configuration through environment variables or gradle properties
  def ttsdk_player_version
  def envVersion = System.getenv('TTSDK_PLAYER_VERSION_FOR_VOD_PLAYER')
  if (envVersion) {
    ttsdk_player_version = envVersion
  } else if (rootProject.hasProperty('TTSDK_PLAYER_VERSION_FOR_VOD_PLAYER')) {
    ttsdk_player_version = rootProject.property('TTSDK_PLAYER_VERSION_FOR_VOD_PLAYER')
  } else {
    // Fallback to versions from package.json
    def packageJson = file("../package.json")
    def slurper = new groovy.json.JsonSlurper()
    def parsedJson = slurper.parseText(packageJson.text)
    def isBp = parsedJson.name.startsWith("@byteplus")
    
    if (isBp) {
      ttsdk_player_version = parsedJson.nativeVersion.byteplus.android
    } else {
      ttsdk_player_version = parsedJson.nativeVersion.volc.android
    }
  }

  def volc_api_engine_version = "1.7.2"
  def volcApiEngineEnvVersion = System.getenv('VOLC_API_ENGINE_VERSION_FOR_VOD_PLAYER')
  if (volcApiEngineEnvVersion) {
    volc_api_engine_version = volcApiEngineEnvVersion
  } else if (rootProject.hasProperty('VOLC_API_ENGINE_VERSION_FOR_VOD_PLAYER')) {
    volc_api_engine_version = rootProject.property('VOLC_API_ENGINE_VERSION_FOR_VOD_PLAYER')
  }
  
  // Decide how to import ttsdk-player based on the return value of useGlobalAppLog()
  if (useGlobalAppLog()) {
    def applog_version = "6.15.4"
    implementation ("com.bytedanceapi:ttsdk-player_${license_type}:${ttsdk_player_version}", {
      exclude group: 'com.bytedance.applog', module: 'RangersAppLog-Lite-cn'
    })
    implementation "com.bytedance.applog:RangersAppLog-Lite-global:${applog_version}"
    logger.info("Using global AppLog with version: ${applog_version}")
  } else {
    implementation "com.bytedanceapi:ttsdk-player_${license_type}:${ttsdk_player_version}"
    logger.info("Using default ttsdk-player implementation")
  }

  implementation "com.bytedanceapi:ttsdk-ttabr:${ttsdk_player_version}"
  implementation "com.volcengine:VolcApiEngine:${volc_api_engine_version}"
//   implementation project(":hybrid-runtime")
  implementation "com.bytedanceapi:ttvideoengine-debugtool:0.3.0.1" 
}
