import com.github.gradle.node.NodeExtension
import com.github.gradle.node.npm.task.NpmTask

plugins {
  id("com.github.node-gradle.node") version "7.1.0"
  id("base") // This adds the standard Gradle lifecycle tasks like "build"
}

node {
  download.set(true)
  // Update to the version that's compatible with your environment requirements
  version.set("20.19.0")
  npmVersion.set("10.2.3") // A compatible npm version for Node.js 20.19.0
  workDir.set(file("${project.projectDir}/node"))
  npmWorkDir.set(file("${project.projectDir}/node"))
}

// Clean the distribution directory
tasks.register<Delete>("cleanDist") {
  description = "Clean the distribution directory"
  delete("dist")
}

// Create a task that will run npm build
tasks.register<com.github.gradle.node.npm.task.NpmTask>("npmBuild") {
  description = "Run 'npm run build'"
  group = "build"

  // Determine which build script to run based on the OS
  val isWindows = System.getProperty("os.name").lowercase().contains("windows")
  npmCommand.set(listOf("run", if (isWindows) "build:dev" else "build:beta"))

  dependsOn("npmInstall")
}

// Add a new task to check Node.js and npm versions
tasks.register<com.github.gradle.node.task.NodeTask>("nodeVersionCheck") {
  description = "Check Node.js and npm versions"
  script.set(file("${projectDir}/node-version-check.js"))

  doFirst {
    // Create a temporary script to check versions
    file("${projectDir}/node-version-check.js").writeText("""
      console.log('Node.js version:', process.version);
      console.log('npm version:', require('npm/package.json').version);
      console.log('Build command that would be used:', process.platform === 'win32' ? 'build:dev' : 'build:beta');
    """.trimIndent())
  }

  doLast {
    // Clean up the temporary script
    delete("${projectDir}/node-version-check.js")
  }
}

tasks.named("assemble") {
  dependsOn("npmBuild")
}
