$ErrorActionPreference = "Stop"

$BaseDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$AppDir = Join-Path $BaseDir "app"
$NodeExe = Join-Path $BaseDir "node\node.exe"
$DataDir = Join-Path $env:LOCALAPPDATA "LiveRushDataCollector\data"
$LogDir = Join-Path $env:LOCALAPPDATA "LiveRushDataCollector\logs"
$LogFile = Join-Path $LogDir "launcher.log"
$ServiceLogFile = Join-Path $LogDir "service.log"
$ServiceStdoutLogFile = Join-Path $LogDir "service.stdout.log"
$ServiceStderrLogFile = Join-Path $LogDir "service.stderr.log"
$Url = "http://127.0.0.1:18766"
$script:ServerProcess = $null
$script:StartedHere = $false

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 Show-StartupError {
  param([string]$Message)
  Write-CollectorLog $Message
  try {
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show($Message, "Live Rush 直播数据采集启动失败", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) | Out-Null
  } 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 Open-CollectorWindow {
  $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=$Url", "--new-window"
      return
    }
  }
  Start-Process $Url
}

function Open-DataFolder {
  if (!(Test-Path $DataDir)) { New-Item -ItemType Directory -Force -Path $DataDir | Out-Null }
  Start-Process $DataDir
}

function Start-CollectorService {
  if (Test-CollectorReady) { Write-CollectorLog "collector service already ready"; return }
  if (!(Test-Path $NodeExe)) { throw "找不到内置 Node 运行文件：$NodeExe" }
  $ScriptPath = Join-Path $AppDir "tools\scripts\serve-live-data-collector-plugin-bootstrap.mjs"
  if (!(Test-Path $ScriptPath)) { throw "找不到采集服务脚本：$ScriptPath" }
  if (!(Test-Path $DataDir)) { New-Item -ItemType Directory -Force -Path $DataDir | Out-Null }
  if (!(Test-Path $LogDir)) { New-Item -ItemType Directory -Force -Path $LogDir | Out-Null }
  $psi = New-Object System.Diagnostics.ProcessStartInfo
  $psi.FileName = $NodeExe
  $psi.Arguments = "tools\scripts\serve-live-data-collector-plugin-bootstrap.mjs"
  $psi.WorkingDirectory = $AppDir
  $psi.UseShellExecute = $false
  $psi.CreateNoWindow = $true
  $psi.RedirectStandardOutput = $true
  $psi.RedirectStandardError = $true
  $psi.EnvironmentVariables["LIVE_RUSH_COLLECTOR_DATA_DIR"] = $DataDir
  $psi.EnvironmentVariables["LIVE_RUSH_COLLECTOR_PORT"] = "18766"
  $psi.EnvironmentVariables["LIVE_RUSH_COLLECTOR_LOG_FILE"] = $ServiceLogFile
  $script:ServerProcess = [System.Diagnostics.Process]::Start($psi)
  $script:StartedHere = $true
  Start-Sleep -Milliseconds 900
  if ($script:ServerProcess.HasExited) {
    try {
      $stdout = $script:ServerProcess.StandardOutput.ReadToEnd()
      $stderr = $script:ServerProcess.StandardError.ReadToEnd()
      if ($stdout) { Add-Content -Path $ServiceStdoutLogFile -Value $stdout -Encoding UTF8 }
      if ($stderr) { Add-Content -Path $ServiceStderrLogFile -Value $stderr -Encoding UTF8 }
    } catch {}
    throw "采集服务启动后退出，退出码：$($script:ServerProcess.ExitCode)。日志：$LogFile；服务日志：$ServiceLogFile；错误输出：$ServiceStderrLogFile"
  }
  Write-CollectorLog "collector service started pid=$($script:ServerProcess.Id)"
}

function Stop-CollectorService {
  if ($script:StartedHere -and $script:ServerProcess -and !$script:ServerProcess.HasExited) {
    try { $script:ServerProcess.Kill() } catch {}
  }
}

try {
  Write-CollectorLog "launcher starting from $BaseDir"
  Start-CollectorService
} catch {
  Stop-CollectorService
  Show-StartupError ("Live Rush 直播数据采集服务启动失败：" + $_.Exception.Message + "`r`n日志位置：" + $LogFile)
  exit 1
}

try {
  Add-Type -AssemblyName System.Windows.Forms
  Add-Type -AssemblyName System.Drawing
  $notify = New-Object System.Windows.Forms.NotifyIcon
  $notify.Icon = [System.Drawing.SystemIcons]::Application
  $notify.Text = "Live Rush 数据采集中"
  $notify.Visible = $true

  $menu = New-Object System.Windows.Forms.ContextMenuStrip
  $openItem = $menu.Items.Add("打开采集页面")
  $folderItem = $menu.Items.Add("打开数据目录")
  $menu.Items.Add("-") | Out-Null
  $exitItem = $menu.Items.Add("退出采集程序")
  $openItem.add_Click({ Open-CollectorWindow })
  $folderItem.add_Click({ Open-DataFolder })
  $exitItem.add_Click({
    $answer = [System.Windows.Forms.MessageBox]::Show("直播期间退出会停止主线和备线采集。确定要退出吗？", "退出 Live Rush 直播数据采集", [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Warning)
    if ($answer -ne [System.Windows.Forms.DialogResult]::Yes) { return }
    Stop-CollectorService
    $notify.Visible = $false
    [System.Windows.Forms.Application]::Exit()
  })
  $notify.ContextMenuStrip = $menu
  $notify.add_DoubleClick({ Open-CollectorWindow })
  $notify.ShowBalloonTip(5000, "Live Rush 数据采集", "程序已在后台运行。双击右下角图标可打开采集页面。", [System.Windows.Forms.ToolTipIcon]::Info)

  [System.Windows.Forms.Application]::Run()
  $notify.Dispose()
} catch {
  Stop-CollectorService
  Show-StartupError ("采集服务已尝试启动，但右下角托盘启动失败：" + $_.Exception.Message + "`r`n已停止后台采集服务，请打开开始菜单里的诊断启动。`r`n日志位置：" + $LogFile)
  exit 1
}
