param(
    [string]$ListenAddress = "0.0.0.0",
    [int]$Port = 8010,
    [string]$WslIp = "",
    [string]$RuleName = ""
)

$ErrorActionPreference = "Stop"

if ([string]::IsNullOrWhiteSpace($RuleName)) {
    $RuleName = "MyIntranetApp-$Port"
}

if ([string]::IsNullOrWhiteSpace($WslIp)) {
    $detected = wsl.exe hostname -I 2>$null
    if (-not $detected) {
        throw "WSL IP를 자동으로 찾지 못했습니다. -WslIp 옵션으로 직접 지정해 주세요."
    }

    $WslIp = (($detected -split "\s+") | Where-Object { $_ -match '^\d+\.\d+\.\d+\.\d+$' } | Select-Object -First 1)
    if (-not $WslIp) {
        throw "WSL IP를 자동으로 파싱하지 못했습니다. -WslIp 옵션으로 직접 지정해 주세요."
    }
}

Write-Host "Setting Windows portproxy for WSL app..." -ForegroundColor Cyan
Write-Host "ListenAddress: $ListenAddress"
Write-Host "Port: $Port"
Write-Host "WSL IP: $WslIp"

$windowsIps = Get-NetIPAddress -AddressFamily IPv4 |
    Where-Object {
        $_.IPAddress -notlike '127.*' `
            -and $_.IPAddress -notlike '169.254*' `
            -and $_.InterfaceAlias -notlike '*WSL*'
    } |
    Select-Object -ExpandProperty IPAddress

$listenAddresses = @($ListenAddress)
if ($ListenAddress -eq "0.0.0.0") {
    $listenAddresses += $windowsIps
}
$listenAddresses = $listenAddresses | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique

foreach ($address in $listenAddresses) {
    netsh interface portproxy delete v4tov4 listenport=$Port listenaddress=$address | Out-Null
    netsh interface portproxy add v4tov4 listenport=$Port listenaddress=$address connectport=$Port connectaddress=$WslIp
}

$existingRule = Get-NetFirewallRule -DisplayName $RuleName -ErrorAction SilentlyContinue
if ($existingRule) {
    Remove-NetFirewallRule -DisplayName $RuleName | Out-Null
}

New-NetFirewallRule `
    -DisplayName $RuleName `
    -Direction Inbound `
    -Action Allow `
    -Protocol TCP `
    -LocalPort $Port | Out-Null

Write-Host ""
Write-Host "Completed." -ForegroundColor Green
Write-Host "Now open this from another PC on the intranet:"
if ($windowsIps) {
    foreach ($ip in $windowsIps) {
        Write-Host "http://$ip`:$Port"
    }
} else {
    Write-Host "http://<Windows-IP>:$Port"
}
Write-Host ""
Write-Host "Tip: if WSL restarts and its IP changes, run this script again. If you omit -WslIp, the script will detect it automatically."
