import org.jetbrains.kotlin.MPPTools
import org.jetbrains.kotlin.PlatformInfo
import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType

buildscript {
    ext.rootBuildDirectory = file('../..')
    apply from: "$rootProject.projectDir/../gradle/kotlinGradlePlugin.gradle"
}

apply plugin: 'kotlin-multiplatform'


def toolsPath = '../../tools'
def frameworkName = 'benchmarksAnalyzer'

def buildType = NativeBuildType.valueOf(findProperty('nativeBuildType') ?: 'DEBUG')

def archSuffix = PlatformInfo.hostName.substring(PlatformInfo.hostName.lastIndexOf('_') + 1).capitalize()

kotlin {
    sourceSets {
        commonMain {
            kotlin.srcDir "$toolsPath/benchmarks/shared/src"
            kotlin.srcDir "$toolsPath/benchmarksAnalyzer/src/main/kotlin"
            kotlin.srcDir "$rootProject.projectDir/../endorsedLibraries/kotlinx.cli/src/main/kotlin"
        }
        nativeMain {
            dependsOn commonMain
            kotlin.srcDir "$rootProject.projectDir/../endorsedLibraries/kotlinx.cli/src/main/kotlin-native"
            kotlin.srcDir "$toolsPath/benchmarksAnalyzer/src/main/kotlin-native"
        }
        macosX64Main { dependsOn nativeMain }
        macosArm64Main { dependsOn nativeMain }
    }

    configure([macosX64(), macosArm64()]) {
        compilations.main.cinterops {
            libcurl {
                defFile "$toolsPath/benchmarksAnalyzer/src/nativeInterop/cinterop/libcurl.def"
            }
        }
    }

    macosX64().binaries {
        framework(frameworkName, [buildType])
    }

    macosArm64().binaries {
        framework(frameworkName, [buildType])
    }
}

MPPTools.addTimeListener(project)

task konanRun {
    if (PlatformInfo.isMac()) {
        dependsOn "linkBenchmarksAnalyzerDebugFrameworkMacos${archSuffix}"
    }
}

/**
 * TODO: it would be better to make help function generating such nop task in buildSrc.
 */
task jvmRun  {
    doLast {
        println("JVM run is unsupported")
    }
}

def compilerFlags(def buildType) {
    def result = []
    if (buildType.optimized) {
        result.add("-opt")
    }
    if (buildType.debuggable) {
        result.add("-g")
    }
    return result
}

def getMacTarget() {
    if (PlatformInfo.isMac()) {
        if (PlatformInfo.hostName == "macos_x64")
           return kotlin.macosX64("macosX64")
        else return kotlin.macosArm64("macosArm64")
    }
    throw new GradleException('Current host isn\'t run with Mac OS')
}

task konanJsonReport {
    doLast {
        if (PlatformInfo.isMac()) {
            def applicationName = "FrameworkBenchmarksAnalyzer"
            def macTarget = getMacTarget()
            def frameworkPath = macTarget.binaries.
                    getFramework(frameworkName, macTarget.binaries.DEBUG).outputFile.absolutePath
            def nativeExecutable = new File("$frameworkPath/$frameworkName").canonicalPath
            def nativeCompileTime = MPPTools.getNativeCompileTime(project, applicationName, ["compileKotlinMacos${archSuffix}".toString(),
                                                                                    "linkBenchmarksAnalyzerDebugFrameworkMacos${archSuffix}".toString(),
                                                                                    "cinteropLibcurlMacos${archSuffix}".toString()])
            def properties = getCommonProperties() + ['type'           : 'native',
                                                      'compilerVersion': "${kotlinVersion}".toString(),
                                                      'flags'          : compilerFlags(buildType).sort(),
                                                      'benchmarks'     : '[]',
                                                      'compileTime'    : [nativeCompileTime],
                                                      'codeSize'       : MPPTools.getCodeSizeBenchmark(applicationName, nativeExecutable)]
            def output = MPPTools.createJsonReport(properties)
            layout.buildDirectory.file(nativeJson).get().asFile.write(output)
        }
    }
}

task jvmJsonReport {
    doLast {
        println("JVM run is unsupported")
    }
}

jvmRun.finalizedBy jvmJsonReport
konanRun.finalizedBy konanJsonReport

private def getCommonProperties() {
    return ['cpu': System.getProperty("os.arch"),
            'os': System.getProperty("os.name"), // OperatingSystem.current().getName()
            'jdkVersion': System.getProperty("java.version"), // org.gradle.internal.jvm.Jvm.current().javaVersion
            'jdkVendor': System.getProperty("java.vendor"),
            'kotlinVersion': "${kotlinVersion}".toString()]
}
