import org.apache.tools.ant.taskdefs.condition.Os

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

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

expoModule {
  canBePublished false
}

def isEnabled = System.getenv('EXPO_UNSTABLE_LOG_BOX') == '1' || System.getenv('EXPO_UNSTABLE_LOG_BOX')?.toLowerCase() == 'true'

android {
  namespace "expo.modules.logbox"
  defaultConfig {
    versionCode 1
    versionName "57.0.4"
    buildConfigField "boolean", "EXPO_UNSTABLE_LOG_BOX", isEnabled ? "true" : "false"
  }

  sourceSets {
    main {
      java.srcDirs += "src/main"
    }
    if (isEnabled) {
      debug {
        // dist contains only ExpoLogBox.bundle
        assets.srcDirs += "${projectDir}/../dist"
      }
    }
  }

  aaptOptions {
    ignoreAssetsPattern '!._expo'
  }
}

dependencies {
  implementation 'com.facebook.react:react-android'
  implementation 'com.google.android.material:material:1.13.0'
  implementation 'com.squareup.okhttp3:okhttp:3.14.9'
  implementation 'com.google.code.gson:gson:2.8.6'
}

def expoLogBoxDirFile = project.projectDir.parentFile
def expoLogBoxDir = expoLogBoxDirFile.absolutePath

def config = project.hasProperty("react") ? project.react : [];
def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]

afterEvaluate {
  def distDirFile = file("${expoLogBoxDir}/dist")
  def bundleOnDemandFlagFile = file("${expoLogBoxDir}/.bundle-on-demand")

  if (bundleOnDemandFlagFile.exists()) {
    def createExpoLogBoxBundleTask = tasks.register('createExpoLogBoxBundle', Exec) {
      description = 'expo-log-box: Create bundle.'

      // Setup inputs and output so Gradle can cache the ExpoLogBox.bundle
      inputs.dir project.fileTree(expoLogBoxDirFile) {
        exclude 'dist/**'
        exclude 'android/**'
        // Including node_modules causes Gradle to hash thousands of files from the pnpm store
        // for up-to-date checks, leading to OOM. If only a dependency changes (no source file
        // edits), a clean build is needed to pick it up.
        exclude 'node_modules/**'
      }
      outputs.dir distDirFile

      // Generate the bundle
      if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        commandLine("cmd", "/c", *nodeExecutableAndArgs, "$expoLogBoxDir/scripts/build-bundle.mjs")
      } else {
        commandLine(*nodeExecutableAndArgs, "$expoLogBoxDir/scripts/build-bundle.mjs")
      }
    }

    // Generate bundle at preBuild
    tasks.getByName('preBuild').dependsOn(createExpoLogBoxBundleTask)
  }
}
