param(
  [switch]$DebugClient,
  [switch]$SetupOnly
)

$ErrorActionPreference = "Stop"

function Find-RuneLiteHome {
  $candidates = @()
  if ($env:RUNELITE_HOME) { $candidates += $env:RUNELITE_HOME }
  $candidates += Join-Path $env:LOCALAPPDATA "RuneLite"
  if ($env:ProgramFiles) { $candidates += (Join-Path $env:ProgramFiles "RuneLite") }
  $pf86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)")
  if ($pf86) { $candidates += (Join-Path $pf86 "RuneLite") }
  foreach ($dir in $candidates) {
    $java = Join-Path $dir "jre\bin\java.exe"
    if (Test-Path $java) { return $dir }
  }
  return $null
}

function Find-JagexLauncher {
  foreach ($p in @(
      "${env:ProgramFiles(x86)}\Jagex Launcher\JagexLauncher.exe",
      "$env:ProgramFiles\Jagex Launcher\JagexLauncher.exe"
    )) {
    if (Test-Path $p) { return $p }
  }
  return $null
}

function Test-JagexCreds([string]$path) {
  if (-not (Test-Path $path)) { return $false }
  $raw = Get-Content $path -Raw -ErrorAction SilentlyContinue
  return [bool]($raw -match 'JX_SESSION_ID=\S+')
}

function Ensure-RuneLiteDumpFlag {
  $rlDir = Join-Path $env:LOCALAPPDATA "RuneLite"
  if (-not (Test-Path $rlDir)) {
    throw "RuneLite is not installed. Install it from https://runelite.net first."
  }
  $settingsPath = Join-Path $rlDir "settings.json"
  $flag = "--insecure-write-credentials"
  $obj = $null
  if (Test-Path $settingsPath) {
    $raw = [IO.File]::ReadAllText($settingsPath).Trim([char]0xFEFF)
    try { $obj = $raw | ConvertFrom-Json } catch { $obj = $null }
  }
  if (-not $obj) {
    $obj = [pscustomobject]@{
      noupdates                 = $false
      clientArguments           = @($flag)
      nodiffs                   = $false
      debug                     = $false
      safemode                  = $false
      skipTlsVerification       = $false
      hardwareAccelerationMode  = "AUTO"
      launchMode                = "AUTO"
      jvmArguments              = @()
      ipv4                      = $false
    }
  }
  else {
    $args = @()
    if ($null -ne $obj.clientArguments) { $args = @($obj.clientArguments) }
    if ($args -contains $flag) { return }
    $args += $flag
    $obj | Add-Member -NotePropertyName clientArguments -NotePropertyValue $args -Force
  }
  $json = $obj | ConvertTo-Json -Depth 6
  [IO.File]::WriteAllText($settingsPath, $json, [Text.UTF8Encoding]::new($false))
}

function Ensure-JagexCredentials([string]$creds) {
  if (Test-JagexCreds $creds) { return }
  Ensure-RuneLiteDumpFlag
  $jagex = Find-JagexLauncher
  if (-not $jagex) {
    throw "Jagex Launcher not found. Install it, then run OSRS Control Session.exe again."
  }
  Start-Process $jagex | Out-Null

  $waiter = Join-Path $env:TEMP "vanguard-jagex-wait.ps1"
  $credsEsc = $creds.Replace("'", "''")
  @"
`$ErrorActionPreference = 'Continue'
`$creds = '$credsEsc'
`$deadline = (Get-Date).AddMinutes(10)
Write-Host ''
Write-Host '  VanguardBOT setup'
Write-Host '  -----------------'
Write-Host '  Jagex Launcher should be open.'
Write-Host '  Log in if needed, then click PLAY on Old School.'
Write-Host ''
Write-Host '  Waiting... this window closes by itself.'
Write-Host '  Press Ctrl+C to cancel.'
Write-Host ''
while ((Get-Date) -lt `$deadline) {
  if (Test-Path `$creds) {
    `$raw = Get-Content `$creds -Raw -ErrorAction SilentlyContinue
    if (`$raw -match 'JX_SESSION_ID=\S+') {
      Write-Host '  Login saved. You can close RuneLite if it opened.'
      Start-Sleep -Seconds 2
      exit 0
    }
  }
  Start-Sleep -Seconds 2
}
Write-Host '  Timed out. Click PLAY on Old School in Jagex Launcher, then try again.'
Start-Sleep -Seconds 6
exit 1
"@ | Set-Content -Path $waiter -Encoding UTF8

  $p = Start-Process -FilePath "powershell.exe" -ArgumentList @(
    "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $waiter
  ) -Wait -PassThru -WindowStyle Normal
  Remove-Item $waiter -Force -ErrorAction SilentlyContinue
  if ($p.ExitCode -ne 0 -or -not (Test-JagexCreds $creds)) {
    throw "Jagex login was not saved. Open Jagex Launcher, click PLAY on Old School, then run this again."
  }
}

$rlHome = Find-RuneLiteHome
if (-not $rlHome) {
  throw "RuneLite is not installed. Install RuneLite from https://runelite.net first."
}

$java = Join-Path $rlHome "jre\bin\java.exe"
$repo = Join-Path $env:USERPROFILE ".runelite\repository2"
$creds = Join-Path $env:USERPROFILE ".runelite\credentials.properties"
$sideDir = Join-Path $env:USERPROFILE ".runelite\sideloaded-plugins"
$side = Join-Path $sideDir "osrs-control-plugin-1.0.0.jar"
$packRoot = Split-Path $PSScriptRoot -Parent
$jarName = "osrs-control-plugin-1.0.0.jar"
$built = @(
  (Join-Path $packRoot $jarName),
  (Join-Path $packRoot "plugin\$jarName"),
  (Join-Path $packRoot "build\libs\$jarName"),
  (Join-Path $PSScriptRoot $jarName)
) | Where-Object { Test-Path $_ } | Select-Object -First 1

Ensure-JagexCredentials $creds
if ($SetupOnly) {
  Write-Host "Jagex login is ready."
  return
}

if ($built) {
  New-Item -ItemType Directory -Path $sideDir -Force | Out-Null
  Copy-Item $built $side -Force
}
if (-not (Test-Path $java)) { throw "JRE missing: $java" }
if (-not (Test-Path $side)) { throw "plugin jar missing: $side (run Install plugin.bat first)" }
if (-not (Test-Path $repo)) { throw "RuneLite repository missing. Open RuneLite once via Jagex Launcher first." }

Get-Content $creds | ForEach-Object {
  $i = $_.IndexOf("=")
  if ($i -gt 0) {
    Set-Item -Path ("Env:" + $_.Substring(0,$i).Trim()) -Value $_.Substring($i+1).Trim()
  }
}

$exclude = @("client-1.12.31.1.jar","runelite-api-1.12.31.1-runtime.jar")
$jars = Get-ChildItem $repo -Filter "*.jar" | Where-Object { $exclude -notcontains $_.Name } | ForEach-Object { $_.FullName }
if (-not $jars) { throw "No RuneLite jars in $repo" }
$cp = ($jars -join ";")
$rlArgs = @(
  "-ea",
  "-Xmx768m",
  "-Xss2m",
  "-XX:CompileThreshold=1500",
  "-Dsun.java2d.d3d=true",
  "-Dsun.java2d.opengl=false",
  "-XX:+DisableAttachMechanism",
  "-cp", $cp,
  "net.runelite.client.RuneLite",
  "--developer-mode",
  "--insecure-write-credentials"
)
if ($DebugClient) {
  $rlArgs += "--debug"
}
$p = Start-Process -FilePath $java -ArgumentList $rlArgs -WorkingDirectory $rlHome -PassThru -WindowStyle Normal
Write-Host "Started control session PID=$($p.Id) log=$(if ($DebugClient) { 'DEBUG' } else { 'INFO' })"
Write-Host "API http://127.0.0.1:5055/  (token: %USERPROFILE%\.runelite\osrs-control-token.txt)"
