# 启动 mitmproxy 抓 TNG Money Packet API（需先: pip install mitmproxy）
$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$Addon = Join-Path $ProjectRoot "debug-server\tng_mmp_mitm_addon.py"

function Get-LanIp {
    $ip = Get-NetIPAddress -AddressFamily IPv4 |
        Where-Object { $_.IPAddress -notlike "127.*" -and $_.InterfaceAlias -notlike "*Loopback*" } |
        Select-Object -First 1 -ExpandProperty IPAddress
    if ($ip) { return $ip }
    return "127.0.0.1"
}

$mitm = Get-Command mitmweb -ErrorAction SilentlyContinue
if (-not $mitm) {
    $mitm = Get-Command mitmdump -ErrorAction SilentlyContinue
}
if (-not $mitm) {
    Write-Host "未找到 mitmproxy。请先安装:" -ForegroundColor Yellow
    Write-Host "  pip install mitmproxy" -ForegroundColor Cyan
    exit 1
}

$pcIp = Get-LanIp
Write-Host ""
Write-Host "=== TNG Money Packet 抓包 ===" -ForegroundColor Cyan
Write-Host "1. 手机与 PC 同一 WiFi" -ForegroundColor White
Write-Host "2. 手机 WiFi 代理: 手动  $pcIp  端口 8888" -ForegroundColor Green
Write-Host "3. 手机浏览器打开 http://mitm.it 安装证书 (Android)" -ForegroundColor White
Write-Host "4. TNG 登录 -> 进群 -> 打开红包 Leaderboard" -ForegroundColor White
Write-Host "5. 命中响应保存到 reverse/dumps/mitm_mmp/" -ForegroundColor White
Write-Host ""
Write-Host "若 TNG 报网络错误，可能是证书 pinning，见 docs 说明。" -ForegroundColor Yellow
Write-Host ""

if ($mitm.Name -eq "mitmweb") {
    Write-Host "Web UI: http://127.0.0.1:8081" -ForegroundColor Cyan
    & mitmweb -s $Addon -p 8888 --web-host 127.0.0.1
} else {
    & mitmdump -s $Addon -p 8888
}
