# Checks host ports from .env (or defaults) before docker compose up.
param(
    [string]$EnvFile = ".env"
)

$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

$defaults = @{
    WEB_PORT     = 3101
    API_PORT     = 5080
    POSTGRES_PORT = 5434
    REDIS_PORT   = 6381
}

$ports = @{}
foreach ($key in $defaults.Keys) { $ports[$key] = $defaults[$key] }

if (Test-Path $EnvFile) {
    Get-Content $EnvFile | ForEach-Object {
        if ($_ -match '^\s*([A-Z_]+)\s*=\s*(\d+)\s*$') {
            $ports[$Matches[1]] = [int]$Matches[2]
        }
    }
}

Write-Host "Meezi port check (from $EnvFile or defaults):" -ForegroundColor Cyan
$blocked = @()

foreach ($name in @("WEB_PORT", "API_PORT", "POSTGRES_PORT", "REDIS_PORT")) {
    $port = $ports[$name]
    $listener = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($listener) {
        Write-Host "  [IN USE]  $name = $port" -ForegroundColor Red
        $blocked += $port
    }
    else {
        Write-Host "  [OK]      $name = $port" -ForegroundColor Green
    }
}

if ($blocked.Count -gt 0) {
    Write-Host ""
    Write-Host "Some ports are busy. Edit .env (copy from .env.example) and pick free ports, then re-run." -ForegroundColor Yellow
    exit 1
}

Write-Host ""
Write-Host "All ports available. Run: docker compose up -d --build" -ForegroundColor Green
exit 0
