param(
  [string]$Url = "http://127.0.0.1:18766",
  [int]$TimeoutSeconds = 60
)

$BaseDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$LauncherPath = Join-Path $BaseDir "Live Rush Data Collector Tray.ps1"
$LogDir = Join-Path $env:LOCALAPPDATA "LiveRushDataCollector\logs"
$LogFile = Join-Path $LogDir "launcher.log"

function Write-CollectorLog {
  param([string]$Message)
  try {
    if (!(Test-Path $LogDir)) { New-Item -ItemType Directory -Force -Path $LogDir | Out-Null }
    $line = "{0} {1}" -f (Get-Date).ToString("s"), $Message
    Add-Content -Path $LogFile -Value $line -Encoding UTF8
  } catch {}
}

function Test-CollectorReady {
  try {
    $response = Invoke-WebRequest -UseBasicParsing -Uri "$Url/api/status" -TimeoutSec 2
    return ($response.StatusCode -ge 200 -and $response.StatusCode -lt 500)
  } catch {
    return $false
  }
}

function Start-CollectorLauncher {
  if (Test-CollectorReady) {
    Write-CollectorLog "control panel requested; collector already ready"
    return
  }
  $powerShellExe = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
  if (!(Test-Path $powerShellExe)) { $powerShellExe = "powershell.exe" }
  Write-CollectorLog "control panel requested; starting launcher from $LauncherPath"
  $quotedLauncherPath = '"' + $LauncherPath + '"'
  Start-Process $powerShellExe -ArgumentList @("-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-File", $quotedLauncherPath)
}

function Open-CollectorWindow {
  param([string]$TargetUrl)
  $programFilesX86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)")
  $edgeCandidates = @()
  if ($env:ProgramFiles) { $edgeCandidates += Join-Path $env:ProgramFiles "Microsoft\Edge\Application\msedge.exe" }
  if ($programFilesX86) { $edgeCandidates += Join-Path $programFilesX86 "Microsoft\Edge\Application\msedge.exe" }
  foreach ($edge in $edgeCandidates) {
    if (Test-Path $edge) {
      Start-Process $edge -ArgumentList "--app=$TargetUrl", "--new-window"
      return
    }
  }
  Start-Process $TargetUrl
}

Start-CollectorLauncher
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
while ((Get-Date) -lt $deadline) {
  try {
    $response = Invoke-WebRequest -UseBasicParsing -Uri $Url -TimeoutSec 2
    if ($response.StatusCode -ge 200 -and $response.StatusCode -lt 500) {
      Write-CollectorLog "collector URL ready; opening control panel"
      Open-CollectorWindow $Url
      exit 0
    }
  } catch {
    Start-Sleep -Milliseconds 700
  }
}

Write-CollectorLog "collector URL did not become ready before timeout"
try {
  Add-Type -AssemblyName System.Windows.Forms
  [System.Windows.Forms.MessageBox]::Show("Live Rush 直播数据采集页面暂时打不开。请把日志发给技术同学：`r`n" + $LogFile, "Live Rush 直播数据采集", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning) | Out-Null
} catch {}
Open-CollectorWindow $Url
exit 1
