# Live Rush Data Collector local PC installer.
# Run in Windows PowerShell on the computer that is also used for TikTok Live Studio.
[CmdletBinding()]
param(
  [string]$InstallerPath = "",
  [string]$RoomInput = "@blazeofficial.msia",
  [string]$TenantLabel = "field_blazeofficial_msia",
  [string]$AlertEmail = "",
  [string]$PrimaryChannel = "",
  [string]$BackupChannel = "",
  [string]$SignApiUrl = "",
  [string]$SignApiKey = "",
  [string]$SmtpHost = "",
  [int]$SmtpPort = 465,
  [bool]$SmtpSsl = $true,
  [string]$SmtpUser = "",
  [string]$SmtpPassword = "",
  [string]$SmtpFrom = "",
  [string]$PublicBaseUrl = "http://127.0.0.1:18766",
  [switch]$Launch = $true,
  [switch]$InstallBackgroundTask = $true,
  [switch]$RestartExisting = $true
)

$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$scriptRoot = if (![string]::IsNullOrWhiteSpace($PSScriptRoot)) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
if ([string]::IsNullOrWhiteSpace($InstallerPath)) { $InstallerPath = Join-Path $scriptRoot "LiveRush-DataCollector-Setup-0.0.0.exe" }

function Write-Step {
  param([string]$Message)
  Write-Host ("[Live Rush] " + $Message)
}

function Set-EnvValue {
  param(
    [hashtable]$Map,
    [string]$Key,
    [string]$Value
  )
  if (![string]::IsNullOrWhiteSpace($Value)) {
    $Map[$Key] = ($Value -replace "`r|`n", "").Trim()
  }
}

function Read-EnvMap {
  param([string]$Path)
  $map = @{}
  if (!(Test-Path $Path)) { return $map }
  foreach ($line in [System.IO.File]::ReadAllLines($Path)) {
    $text = $line.Trim()
    if (!$text -or $text.StartsWith("#") -or !$text.Contains("=")) { continue }
    $index = $text.IndexOf("=")
    $key = $text.Substring(0, $index).Trim().Trim([char]0xFEFF)
    $value = $text.Substring($index + 1).Trim().Trim(@([char]39, [char]34))
    if ($key) { $map[$key] = $value }
  }
  return $map
}

function Write-EnvMap {
  param(
    [string]$Path,
    [hashtable]$Map
  )
  $orderedKeys = @(
    "LIVE_RUSH_TIKTOK_SIGN_API_URL",
    "LIVE_RUSH_TIKTOK_SIGN_API_KEY",
    "LIVE_RUSH_COLLECTOR_PRIMARY_CHANNEL",
    "LIVE_RUSH_COLLECTOR_BACKUP_CHANNEL",
    "LIVE_RUSH_COLLECTOR_ALERT_EMAIL",
    "LIVE_RUSH_COLLECTOR_SMTP_HOST",
    "LIVE_RUSH_COLLECTOR_SMTP_PORT",
    "LIVE_RUSH_COLLECTOR_SMTP_SSL",
    "LIVE_RUSH_COLLECTOR_SMTP_USER",
    "LIVE_RUSH_COLLECTOR_SMTP_PASSWORD",
    "LIVE_RUSH_COLLECTOR_SMTP_FROM",
    "LIVE_RUSH_COLLECTOR_PUBLIC_BASE_URL"
  )
  $lines = @(
    "# Live Rush local collector config. Generated by Install-LiveRushCollector-LocalPC.ps1.",
    "# Keep this file on the collector PC. Do not send it to operators or support chats."
  )
  foreach ($key in $orderedKeys) {
    if ($Map.ContainsKey($key) -and ![string]::IsNullOrWhiteSpace([string]$Map[$key])) {
      $lines += ($key + "=" + [string]$Map[$key])
    }
  }
  $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
  [System.IO.File]::WriteAllLines($Path, $lines, $utf8NoBom)
}

function Stop-ExistingCollector {
  try {
    Stop-ScheduledTask -TaskName "LiveRushDataCollectorBackground" -ErrorAction SilentlyContinue | Out-Null
  } catch {}
  try {
    $targets = Get-CimInstance Win32_Process | Where-Object {
      $_.CommandLine -match "serve-live-data-collector-plugin-bootstrap\.mjs" -or
      $_.CommandLine -match "Live Rush Data Collector Service\.cmd" -or
      $_.CommandLine -match "Live Rush Data Collector Tray\.ps1" -or
      (($_.Name -match "msedge|chrome") -and ($_.CommandLine -match "LiveRushDataCollector\\browser-profile" -or $_.CommandLine -match "remote-debugging-port=9223"))
    }
    foreach ($target in $targets) {
      try { Stop-Process -Id $target.ProcessId -Force -ErrorAction Stop } catch {}
    }
  } catch {}
}

function Register-CollectorBackgroundTask {
  param([string]$InstallDir)
  $serviceCommand = Join-Path $InstallDir "Live Rush Data Collector Service.cmd"
  if (!(Test-Path $serviceCommand)) { throw "找不到后台采集启动脚本：$serviceCommand" }
  try {
    $action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument ('/d /c "' + $serviceCommand + '"') -WorkingDirectory $InstallDir
    $trigger = New-ScheduledTaskTrigger -AtLogOn
    $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit (New-TimeSpan -Days 30) -MultipleInstances IgnoreNew
    try { $settings.Hidden = $true } catch {}
    Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description "Live Rush 直播数据采集后台服务" -Force -ErrorAction Stop | Out-Null
    Write-Step "已配置后台常驻任务：$taskName。"
    return $true
  } catch {
    Write-Step ("后台常驻任务配置失败，改用当前会话启动：" + $_.Exception.Message)
    return $false
  }
}

function Start-CollectorBackgroundService {
  param(
    [string]$InstallDir,
    [bool]$TaskRegistered
  )
  $serviceCommand = Join-Path $InstallDir "Live Rush Data Collector Service.cmd"
  if ($TaskRegistered) {
    try {
      Start-ScheduledTask -TaskName $taskName -ErrorAction Stop
      Start-Sleep -Seconds 3
      Write-Step "后台采集服务已通过常驻任务启动。"
      return
    } catch {
      Write-Step ("常驻任务启动失败，改用当前会话启动：" + $_.Exception.Message)
    }
  }
  Start-Process -FilePath "cmd.exe" -ArgumentList @("/d", "/c", '"' + $serviceCommand + '"') -WorkingDirectory $InstallDir -WindowStyle Hidden
  Start-Sleep -Seconds 3
  Write-Step "后台采集服务已在当前会话启动。"
}

if (!(Test-Path $InstallerPath)) { throw "找不到安装包：$InstallerPath" }
$installDir = Join-Path $env:LOCALAPPDATA "LiveRushDataCollector"
$dataDir = Join-Path $installDir "data"
$envPath = Join-Path $dataDir "email.env"
$settingsPath = Join-Path $dataDir "operator-settings.json"
$taskName = "LiveRushDataCollectorBackground"

Write-Step "开始安装 Live Rush 直播数据采集。"
Start-Process -FilePath $InstallerPath -ArgumentList "/S" -Wait
if (!(Test-Path $installDir)) { throw "安装完成后没有找到目录：$installDir" }
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null

$envMap = Read-EnvMap $envPath
Set-EnvValue $envMap "LIVE_RUSH_TIKTOK_SIGN_API_URL" $SignApiUrl
Set-EnvValue $envMap "LIVE_RUSH_TIKTOK_SIGN_API_KEY" $SignApiKey
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_PRIMARY_CHANNEL" $PrimaryChannel
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_BACKUP_CHANNEL" $BackupChannel
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_ALERT_EMAIL" $AlertEmail
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_SMTP_HOST" $SmtpHost
if ($SmtpPort -gt 0) { Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_SMTP_PORT" ([string]$SmtpPort) }
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_SMTP_SSL" ($(if ($SmtpSsl) { "1" } else { "0" }))
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_SMTP_USER" $SmtpUser
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_SMTP_PASSWORD" $SmtpPassword
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_SMTP_FROM" $SmtpFrom
Set-EnvValue $envMap "LIVE_RUSH_COLLECTOR_PUBLIC_BASE_URL" $PublicBaseUrl
Write-EnvMap $envPath $envMap

$settings = [ordered]@{
  room_input = $RoomInput
  tenant_label = $TenantLabel
  primary_channel = $PrimaryChannel
  backup_channel = $BackupChannel
  alert_email = $AlertEmail
  auto_start = $true
  updated_at = (Get-Date).ToUniversalTime().ToString("o")
}
$settingsJson = $settings | ConvertTo-Json -Depth 4
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($settingsPath, $settingsJson + "`n", $utf8NoBom)

if ($RestartExisting) {
  Write-Step "重启旧采集进程，让新的签名/邮箱/驻守配置生效。"
  Stop-ExistingCollector
}

$taskRegistered = $false
if ($InstallBackgroundTask) {
  $taskRegistered = Register-CollectorBackgroundTask $installDir
}

if ($Launch) {
  Start-CollectorBackgroundService $installDir $taskRegistered
  $launcher = Join-Path $installDir "Live Rush Data Collector.vbs"
  if (!(Test-Path $launcher)) { throw "找不到启动器：$launcher" }
  Write-Step "启动托盘控制入口。"
  Start-Process -FilePath $launcher
  Start-Sleep -Seconds 3
}

Write-Step "安装和本机配置完成。控制页：http://127.0.0.1:18766"
Write-Step "数据目录：$dataDir"
Write-Step "签名通道状态请在控制页的环境检查里确认；这里不会输出密钥。"
