#!/bin/bash
# MPSync — 微信开发者工具 MCP 自动化前置脚本
# 清理残留进程 + 重新开启自动化端口
# 用法: bash scripts/mpsync.sh [-b|--build]

CLI="/d/微信web开发者工具/cli.bat"
DIST="G:/hms/apps/miniprogram/dist"
PORT=9420

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m'

status()  { echo -e "${CYAN}[MPSync]${NC} $1"; }
ok()      { echo -e "${GREEN}[MPSync]${NC} $1"; }
warn()    { echo -e "${YELLOW}[MPSync]${NC} $1"; }

# Step 1: Kill stale DevTools processes (PowerShell 可靠杀进程)
status "Step 1: Killing stale DevTools processes..."
count=$(tasklist 2>/dev/null | grep -c "wechatdevtools.exe" | tr -d '\r\n' || echo "0")
if [ "$count" -gt 0 ]; then
    warn "Found $count stale processes, killing..."
    powershell -Command "Get-Process wechatdevtools -ErrorAction SilentlyContinue | Stop-Process -Force" 2>/dev/null
    sleep 5

    count2=$(tasklist 2>/dev/null | grep -c "wechatdevtools.exe" | tr -d '\r\n' || echo "0")
    if [ "$count2" -gt 0 ]; then
        warn "Still $count2 remaining, second attempt..."
        powershell -Command "Get-Process wechatdevtools -ErrorAction SilentlyContinue | Stop-Process -Force" 2>/dev/null
        sleep 3
    fi
    ok "Cleanup done"
else
    ok "No stale processes"
fi

sleep 2

# Step 2: Optional build
if [ "$1" = "-b" ] || [ "$1" = "--build" ]; then
    status "Building miniprogram..."
    cd "G:/hms/apps/miniprogram" && pnpm build:weapp 2>&1 | tail -3
    ok "Build done"
fi

# Step 3: Start DevTools if not running
running=$(tasklist 2>/dev/null | grep -c "wechatdevtools.exe" | tr -d '\r\n' || echo "0")
if [ "$running" -eq 0 ]; then
    status "Starting DevTools..."
    EXE="/d/微信web开发者工具/微信开发者工具.exe"
    if [ -f "$EXE" ]; then
        "$EXE" "$DIST" &
        status "Waiting for DevTools to initialize (15s)..."
        sleep 15
    else
        warn "Cannot find DevTools exe, please open manually"
    fi
else
    ok "DevTools already running ($running processes)"
fi

# Step 4: Open automation port
status "Opening automation port $PORT..."
"$CLI" auto --project "$DIST" --auto-port $PORT 2>&1

sleep 3

# Step 5: Verify
listening=$(netstat -ano 2>/dev/null | grep ":${PORT}.*LISTEN" | head -1)
if [ -n "$listening" ]; then
    ok "Port $PORT is listening — ready for MCP"
else
    warn "Port $PORT not listening yet, wait a moment..."
fi
