#Requires -RunAsAdministrator
# WSL 与 Docker 网络配置重置脚本
# 需以管理员身份运行

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Continue"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  WSL & Docker 网络配置重置" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 1. 关闭 WSL
Write-Host "[1/5] 关闭 WSL..." -ForegroundColor Yellow
wsl --shutdown
Start-Sleep -Seconds 3
Write-Host "      完成" -ForegroundColor Green

# 2. 重置 Windows 网络栈（可选，可能需重启）
Write-Host "[2/5] 重置 Windows 网络栈..." -ForegroundColor Yellow
try {
    netsh winsock reset 2>$null
    netsh int ip reset 2>$null
    Write-Host "      完成 (如有提示重启，建议执行)" -ForegroundColor Green
} catch {
    Write-Host "      跳过: $($_.Exception.Message)" -ForegroundColor Gray
}

# 3. 清理 Docker 网络
Write-Host "[3/5] 清理 Docker 未使用网络..." -ForegroundColor Yellow
$dockerOk = $false
try {
    $null = docker info 2>&1
    $dockerOk = $true
} catch { }
if ($dockerOk) {
    docker network prune -f 2>$null
    Write-Host "      完成" -ForegroundColor Green
} else {
    Write-Host "      跳过 (Docker 未运行，请先启动 Docker Desktop)" -ForegroundColor Gray
}

# 4. 清除 Docker 端口代理残留（若有）
Write-Host "[4/5] 检查端口代理..." -ForegroundColor Yellow
$proxies = netsh interface portproxy show all 2>$null
if ($proxies -and $proxies -match "3010|3001|3002|3003") {
    Write-Host "      发现相关端口代理，请手动在管理员 CMD 执行:" -ForegroundColor Yellow
    Write-Host "      netsh interface portproxy reset" -ForegroundColor White
} else {
    Write-Host "      无异常端口代理" -ForegroundColor Green
}

# 5. 提示
Write-Host "[5/5] 下一步操作:" -ForegroundColor Yellow
Write-Host ""
Write-Host "  1. 启动 Docker Desktop（若已关闭）" -ForegroundColor White
Write-Host "  2. 等待 Docker 完全就绪后，执行:" -ForegroundColor White
Write-Host "     cd D:\01一键部署包\easyai" -ForegroundColor Cyan
Write-Host "     docker compose up -d" -ForegroundColor Cyan
Write-Host ""
Write-Host "  3. 若端口仍不可访问，在 Docker Desktop 中:" -ForegroundColor White
Write-Host "     [设置] -> [Troubleshoot] -> [Reset to factory defaults]" -ForegroundColor Cyan
Write-Host "     (会清除所有容器/镜像，谨慎使用)" -ForegroundColor Gray
Write-Host ""
Write-Host "  4. 若执行了 netsh winsock/int ip reset，建议重启电脑" -ForegroundColor White
Write-Host ""
Read-Host "按 Enter 键退出"
