# MPSync — auto clean stale DevTools + open automation port
# Usage: powershell -File scripts/mpsync.ps1 [-Build]
param([switch]$Build)

$Port = 9420

Write-Host "[MPSync] Step 1: Kill stale DevTools processes..." -ForegroundColor Cyan
$procs = Get-Process -Name "wechatdevtools" -ErrorAction SilentlyContinue
if ($null -ne $procs) {
    Write-Host "[MPSync] Found $($procs.Count) stale processes, killing..." -ForegroundColor Yellow
    Stop-Process -Name "wechatdevtools" -Force -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 5
    $left = Get-Process -Name "wechatdevtools" -ErrorAction SilentlyContinue
    if ($null -ne $left) {
        Write-Host "[MPSync] Still $($left.Count) remaining, second attempt..." -ForegroundColor Yellow
        Stop-Process -Name "wechatdevtools" -Force -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 3
    }
    Write-Host "[MPSync] Cleanup done" -ForegroundColor Green
} else {
    Write-Host "[MPSync] No stale processes" -ForegroundColor Green
}

Start-Sleep -Seconds 2

# Optional build
if ($Build) {
    Write-Host "[MPSync] Building miniprogram..." -ForegroundColor Cyan
    Set-Location "G:\hms\apps\miniprogram"
    pnpm build:weapp 2>&1 | Select-Object -Last 3
    Write-Host "[MPSync] Build done" -ForegroundColor Green
}

# Open DevTools with project
$DevToolsExe = "D:\微信web开发者工具\微信web开发者工具.exe"
$DistPath = "G:\hms\apps\miniprogram\dist"

$running = Get-Process -Name "wechatdevtools" -ErrorAction SilentlyContinue
if ($null -eq $running) {
    Write-Host "[MPSync] Starting DevTools..." -ForegroundColor Cyan
    Start-Process $DevToolsExe -ArgumentList $DistPath
    Write-Host "[MPSync] Waiting for DevTools to initialize..." -ForegroundColor Cyan
    Start-Sleep -Seconds 15
} else {
    Write-Host "[MPSync] DevTools already running ($($running.Count) processes)" -ForegroundColor Green
}

# Open automation port via CLI
Write-Host "[MPSync] Opening automation port $Port..." -ForegroundColor Cyan
$cliShort = (New-Object -ComObject Scripting.FileSystemObject).GetFile("D:\微信web开发者工具\cli.bat").ShortPath
$cliResult = & $cliShort auto --project $DistPath --auto-port $Port 2>&1
$cliResult | ForEach-Object { Write-Host $_ }

Start-Sleep -Seconds 3

# Verify port
$listener = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
if ($null -ne $listener) {
    Write-Host "[MPSync] Port $Port is listening - ready for MCP" -ForegroundColor Green
} else {
    Write-Host "[MPSync] WARNING: Port $Port not listening yet" -ForegroundColor Yellow
}
