@echo off
chcp 936 >nul 2>&1
setlocal
set "BASE=https://work.ishoushu.com"
set "CRAWL=%LOCALAPPDATA%\ShuzhiCrawler"
set "LOG=%CRAWL%\repair.log"
title 书智采集器 一键修复
if not exist "%CRAWL%" mkdir "%CRAWL%" >nul 2>&1

echo.
echo  ============================================
echo    书智采集器 一键修复（约 30 秒）
echo    修完桌面上不会再自动弹窗口
echo  ============================================
echo.

echo  [1/5] 停掉旧的（包括反复弹窗的那些）...
taskkill /f /im shuzhi-crawler.exe >nul 2>&1
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -like '*shuzhi-crawl-agent*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }" >>"%LOG%" 2>&1
schtasks /End /TN ShuzhiCrawlerAgent >nul 2>&1
schtasks /Delete /TN ShuzhiCrawlerAgent /F >nul 2>&1
timeout /t 2 /nobreak >nul 2>&1

echo  [2/5] 下载运行环境（第一次要 70M，慢一点）...
if not exist "%CRAWL%\node.exe" (
  curl -L --fail --retry 2 --connect-timeout 20 -o "%CRAWL%\node.new.exe" "%BASE%/download/agent/node.exe" >>"%LOG%" 2>&1
  if not exist "%CRAWL%\node.new.exe" powershell -NoProfile -Command "try{Invoke-WebRequest -UseBasicParsing -Uri '%BASE%/download/agent/node.exe' -OutFile '%CRAWL%\node.new.exe'}catch{exit 1}" >>"%LOG%" 2>&1
  if not exist "%CRAWL%\node.new.exe" (
    echo        下载没成功，检查网络后再点一次
    goto :done
  )
  move /y "%CRAWL%\node.new.exe" "%CRAWL%\node.exe" >nul 2>&1
)

echo  [3/5] 下载最新采集程序...
del /q "%CRAWL%\agent.new.js" >nul 2>&1
curl -L --fail --retry 2 --connect-timeout 20 -o "%CRAWL%\agent.new.js" "%BASE%/download/agent/shuzhi-crawl-agent.js?v=0320" >>"%LOG%" 2>&1
if not exist "%CRAWL%\agent.new.js" powershell -NoProfile -Command "try{Invoke-WebRequest -UseBasicParsing -Uri '%BASE%/download/agent/shuzhi-crawl-agent.js?v=0320' -OutFile '%CRAWL%\agent.new.js'}catch{exit 1}" >>"%LOG%" 2>&1
if not exist "%CRAWL%\agent.new.js" (
  echo        下载没成功，检查网络后再点一次
  goto :done
)
move /y "%CRAWL%\agent.new.js" "%CRAWL%\shuzhi-crawl-agent.js" >nul 2>&1
del /q "%CRAWL%\hidden-tried.ok" "%CRAWL%\hidden-task.ok" >nul 2>&1
echo        采集程序已就位

echo  [4/5] 装上"后台静默 + 掉线自己回来"...
> "%CRAWL%\repair-task.ps1" echo $ErrorActionPreference = 'SilentlyContinue'
>>"%CRAWL%\repair-task.ps1" echo $d = Join-Path $env:LOCALAPPDATA 'ShuzhiCrawler'
>>"%CRAWL%\repair-task.ps1" echo $n = Join-Path $d 'node.exe'
>>"%CRAWL%\repair-task.ps1" echo $j = Join-Path $d 'shuzhi-crawl-agent.js'
>>"%CRAWL%\repair-task.ps1" echo $v = Join-Path $d 'launch-hidden.vbs'
>>"%CRAWL%\repair-task.ps1" echo $l1 = 'Set sh = CreateObject("WScript.Shell")'
>>"%CRAWL%\repair-task.ps1" echo $l2 = 'sh.CurrentDirectory = "' + $d + '"'
>>"%CRAWL%\repair-task.ps1" echo $l3 = 'sh.Run """' + $n + '"" ""' + $j + '""", 0, False'
>>"%CRAWL%\repair-task.ps1" echo $code = ($l1,$l2,$l3) -join ([char]13 + [char]10)
>>"%CRAWL%\repair-task.ps1" echo Set-Content -Path $v -Value $code -Encoding ASCII
>>"%CRAWL%\repair-task.ps1" echo Unregister-ScheduledTask -TaskName 'ShuzhiCrawlerAgent' -Confirm:$false -ErrorAction SilentlyContinue
>>"%CRAWL%\repair-task.ps1" echo $a = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('"' + $v + '"') -WorkingDirectory $d
>>"%CRAWL%\repair-task.ps1" echo $t1 = New-ScheduledTaskTrigger -AtLogOn
>>"%CRAWL%\repair-task.ps1" echo $t2 = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Days 3650)
>>"%CRAWL%\repair-task.ps1" echo $s = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)
>>"%CRAWL%\repair-task.ps1" echo Register-ScheduledTask -TaskName 'ShuzhiCrawlerAgent' -Action $a -Trigger $t1,$t2 -Settings $s -RunLevel Highest -Force
>>"%CRAWL%\repair-task.ps1" echo Start-ScheduledTask -TaskName 'ShuzhiCrawlerAgent'
powershell -NoProfile -ExecutionPolicy Bypass -File "%CRAWL%\repair-task.ps1"
echo        已改成后台静默启动（不再弹黑框）

echo  [5/5] 等它连上 ...
timeout /t 18 /nobreak >nul 2>&1
echo.
echo  ============================================
powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -like '*shuzhi-crawl-agent*' } | ForEach-Object { Write-Host ('    采集器在跑  PID ' + $_.ProcessId) }"
powershell -NoProfile -Command "$t = Get-ScheduledTask -TaskName 'ShuzhiCrawlerAgent' -ErrorAction SilentlyContinue; if ($t) { Write-Host ('    计划任务已装好（执行：' + $t.Actions[0].Execute + '）') } else { Write-Host '    计划任务没装上，请再点一次本文件' }"
echo.
echo    这个窗口可以直接关。
echo    以后它在后台自己活着、掉线自己回来、换新版自己换，看不到窗口。
echo  ============================================

:done
echo.
pause
