#!/usr/bin/env pwsh

$ErrorActionPreference = "Stop"

# --- Resolve RUMI_CLI_HOME ---
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$RUMI_CLI_HOME = Resolve-Path "$ScriptDir/.." | ForEach-Object { $_.Path }

# --- Check JAVA_HOME ---
if (-not $env:JAVA_HOME) {
    Write-Host "The JAVA_HOME environment variable needs to be set."
    exit 1
}

# --- Check Java version ---
$java = Join-Path $env:JAVA_HOME "bin\java.exe"
if (-Not (Test-Path $java)) {
    throw "Could not find Java executable at $java"
}
$procInfo = New-Object System.Diagnostics.ProcessStartInfo
$procInfo.FileName = $java
$procInfo.Arguments = "-version"
$procInfo.RedirectStandardError = $true
$procInfo.UseShellExecute = $false
$procInfo.CreateNoWindow = $true
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo = $procInfo
$proc.Start() | Out-Null
$javaVersionOutput = $proc.StandardError.ReadToEnd()
$proc.WaitForExit()
if ($javaVersionOutput -match '"(\d+(?:\.\d+){1,2}(?:_\d+)?)"') {
    $javaVersion = $Matches[1]
    if ($javaVersion.StartsWith("1.")) {
        $majorVersion = [int]($javaVersion.Split('.')[1])
    } else {
        $majorVersion = [int]($javaVersion.Split('.')[0])
    }
    if ($majorVersion -lt 11) {
        Write-Host "The Rumi CLI requires Java version 11 or higher (JAVA_HOME currently points to $javaVersion)"
        exit 1
    }
} else {
    Write-Host"Could not parse Java version from output:`n$javaVersionOutput"
    exit 1
}

# --- Default trace level ---
$DEFAULTTRACELEVEL = "severe"

# --- Parse arguments ---
$extraJars = ""
$enable3x = $false
$argsList = @()
for ($i = 0; $i -lt $args.Count; $i++) {
    switch ($args[$i]) {
        "--extra-jars" {
            if ($i + 1 -lt $args.Count) {
                $extraJars = $args[$i + 1]
                $i++
            }
        }
        "--3x" {
            $enable3x = $true
        }
        default {
            $argsList += $args[$i]
        }
    }
}

# --- Build classpath ---
$classpath = "$RUMI_CLI_HOME\libs\*"
if ($extraJars) {
    $extraJars.Split(',') | ForEach-Object {
        $classpath += ";$_"
    }
}

# --- Run the CLI ---
$java = Join-Path $env:JAVA_HOME "bin\java.exe"
if (-Not (Test-Path $java)) {
    throw "Could not find Java executable at $java"
}
$cliArgs = @(
    '--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED'
    '--add-opens=java.base/sun.nio.ch=ALL-UNNAMED'
    '--add-opens=java.base/java.lang=ALL-UNNAMED'
    '--add-opens=java.base/java.nio=ALL-UNNAMED'
    '--add-opens=java.base/java.io=ALL-UNNAMED'
    '--add-opens=java.management/sun.management=ALL-UNNAMED'
    '--illegal-access=warn'
    '-Xms1g'
    '-Xmx1g'
    "-Dnv.app.propfile=$RUMI_CLI_HOME\conf\cli.conf"
    "-Dnv.trace.defaultLevel=$DEFAULTTRACELEVEL"
    '-Dnv.cloud.trace=info'
    '-Djava.net.preferIPv4Stack=true'
)
if ($enable3x) {
    $cliArgs += '-Dnv.compat.3x.io=true'
}
$cliArgs += @(
    "-cp", "$classpath",
    'com.neeve.tools.CliMain'
) + $argsList
Start-Process -FilePath $java -ArgumentList $cliArgs -Wait -NoNewWindow
