param([Parameter(Mandatory=$true)][string]$Uri)
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
$Log = Join-Path $Root 'logs\setup.log'

try {
  $u = [System.Uri]$Uri
  if ($u.Scheme -ne 'edgeengine') { throw 'Unsupported protocol' }
  $query = $u.Query.TrimStart('?')
} catch {
  Write-Error 'Invalid Edge Engine launch link.'
  exit 1
}

function Test-EdgeSetup {
  try {
    $r = Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:8787/health' -TimeoutSec 1
    return $r.StatusCode -eq 200
  } catch { return $false }
}

$health = Test-EdgeSetup
if (-not $health) {
  $cmd = Join-Path $Root 'Setup-Edge-Agent.cmd'
  $args = "/d /c set EDGE_AGENT_NO_AUTO_OPEN=1&& `"$cmd`""
  Start-Process -WindowStyle Hidden -FilePath $env:ComSpec -ArgumentList $args
  for ($i=0; $i -lt 40; $i++) {
    Start-Sleep -Milliseconds 250
    if (Test-EdgeSetup) { $health = $true; break }
  }
}

if (-not $health) {
  Add-Type -AssemblyName PresentationFramework
  $detail = if (Test-Path $Log) { "`n`nStartup log:`n$Log" } else { '' }
  [System.Windows.MessageBox]::Show("Edge Agent could not start.$detail`n`nReinstall the latest Edge Agent build, then click Connect Topstep again.",'Edge Engine Agent') | Out-Null
  exit 1
}

$target = 'http://127.0.0.1:8787/setup'
if ($query) { $target += '?' + $query }
Start-Process $target
