$ErrorActionPreference = "Stop"

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$SourceHelperDir = $ScriptDir
$InstallRoot = Join-Path $env:LOCALAPPDATA "NT工作台本机助手"
$TargetHelperDir = Join-Path $InstallRoot "nt-workbench-helper"
$VisibleExtensionDir = Join-Path $InstallRoot "Chrome插件-选择这个文件夹"
$LogDir = Join-Path $InstallRoot "logs"
$WorkBenchUrl = "https://zhuanzhuan-nt.cn/"
$TaskName = "NT Workbench Local Runner"

Write-Host "正在准备 兴趣品类工作台 Windows 本机执行器..."

if (!(Test-Path $SourceHelperDir)) {
  Write-Host "安装包不完整：找不到隐藏程序文件。请重新下载。"
  exit 1
}

$node = Get-Command node -ErrorAction SilentlyContinue
if ($null -eq $node) {
  Write-Host "当前电脑没有安装 Node.js。"
  Write-Host "我会打开 Node.js 下载页。请安装 Node.js 22 或以上版本。"
  Write-Host "安装完成后，回到本文件夹，重新双击「第一步-双击安装并启动.bat」。"
  Start-Process "https://nodejs.org/zh-cn/download"
  exit 1
}

$nodeMajor = [int]((& node -p "Number(process.versions.node.split('.')[0])"))
if ($nodeMajor -lt 22) {
  Write-Host "当前 Node.js 版本低于 22。"
  Write-Host "我会打开 Node.js 下载页。请升级到 Node.js 22 或以上版本。"
  Write-Host "升级完成后，回到本文件夹，重新双击「第一步-双击安装并启动.bat」。"
  Start-Process "https://nodejs.org/zh-cn/download"
  exit 1
}

$nodeExe = $node.Source

$chromeCandidates = @(
  (Join-Path $env:LOCALAPPDATA "Google\Chrome\Application\chrome.exe"),
  (Join-Path $env:ProgramFiles "Google\Chrome\Application\chrome.exe"),
  (Join-Path ${env:ProgramFiles(x86)} "Google\Chrome\Application\chrome.exe")
) | Where-Object { $_ -and (Test-Path $_) }

if ($chromeCandidates.Count -eq 0) {
  Write-Host "没有找到 Google Chrome。请先安装 Chrome 后重新运行。"
  Start-Process "https://www.google.com/chrome/"
  exit 1
}

New-Item -ItemType Directory -Force -Path $InstallRoot, $LogDir | Out-Null

if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) {
  Write-Host "检测到旧版本机执行器正在运行，正在先停止旧版本..."
  Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
  Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}

try {
  $portOwners = Get-NetTCPConnection -LocalPort 4318 -State Listen -ErrorAction SilentlyContinue |
    Select-Object -ExpandProperty OwningProcess -Unique
  foreach ($processId in $portOwners) {
    if ($processId -and $processId -ne $PID) {
      Write-Host "检测到 4318 端口被旧执行器占用，正在清理..."
      Stop-Process -Id $processId -Force -ErrorAction SilentlyContinue
    }
  }
} catch {
  Write-Host "端口占用检查跳过。"
}

if (Test-Path $TargetHelperDir) {
  $backup = Join-Path $InstallRoot ("nt-workbench-helper-backup-" + (Get-Date -Format "yyyyMMdd-HHmmss"))
  Write-Host "检测到旧版本，正在备份到：$backup"
  Move-Item $TargetHelperDir $backup
}

Write-Host "正在复制本机执行器文件..."
Copy-Item $SourceHelperDir $TargetHelperDir -Recurse
if (Test-Path $VisibleExtensionDir) {
  Remove-Item $VisibleExtensionDir -Force -Recurse
}
Copy-Item (Join-Path $TargetHelperDir "chrome-extension") $VisibleExtensionDir -Recurse

Set-Location $TargetHelperDir
if (Test-Path (Join-Path $TargetHelperDir "node_modules\xlsx")) {
  Write-Host "运行依赖已随安装包内置，跳过联网安装。"
} else {
  Write-Host "正在安装运行依赖，通常 1 分钟左右；如果超过 5 分钟，请把窗口截图发给负责人。"
  npm install --omit=dev --registry=https://registry.npmmirror.com
}

$startScript = Join-Path $TargetHelperDir "windows-start-runner.ps1"
$stdoutLog = Join-Path $LogDir "local-runner.log"
$stderrLog = Join-Path $LogDir "local-runner.err.log"

@"
Set-Location "$TargetHelperDir"
`$env:NT_CHROME_EXECUTABLE = "$($chromeCandidates[0])"
& "$nodeExe" local-runner/server.mjs >> "$stdoutLog" 2>> "$stderrLog"
"@ | Set-Content -Path $startScript -Encoding UTF8

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$startScript`""
$trigger = New-ScheduledTaskTrigger -AtLogOn
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel LeastPrivilege
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Principal $principal | Out-Null

Write-Host "正在启动本机执行器..."
Start-ScheduledTask -TaskName $TaskName

$ready = $false
for ($i = 0; $i -lt 20; $i++) {
  try {
    Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:4318/health" -TimeoutSec 2 | Out-Null
    $ready = $true
    break
  } catch {
    Start-Sleep -Seconds 1
  }
}

if (!$ready) {
  Write-Host "本机执行器没有成功启动。请把日志发给负责人排查：$LogDir"
  Start-Process explorer.exe $LogDir
  exit 1
}

Start-Process $WorkBenchUrl
Start-Process "chrome://extensions/"
Start-Process explorer.exe $VisibleExtensionDir

Write-Host ""
Write-Host "本机执行器已启动。"
Write-Host "下一步：在 Chrome 扩展页打开“开发者模式”，加载刚刚打开的「Chrome插件-选择这个文件夹」。"
