$ErrorActionPreference = "Stop"

$root = $PSScriptRoot
$envFile = Join-Path $root ".env"
$envExample = Join-Path $root ".env.example"

Push-Location $root
try {
    if (-not (Test-Path $envFile)) {
        Copy-Item $envExample $envFile
        Write-Host "[prod-local] .env not found, copied from .env.example"
    }

    $config = @{}
    Get-Content $envFile | ForEach-Object {
        $line = $_.Trim()
        if ($line -and -not $line.StartsWith("#") -and $line.Contains("=")) {
            $index = $line.IndexOf("=")
            $key = $line.Substring(0, $index).Trim()
            $value = $line.Substring($index + 1).Trim()
            $config[$key] = $value
        }
    }
    function Get-ConfigValue($key, $fallback) {
        if ($config.ContainsKey($key) -and $config[$key]) {
            return $config[$key]
        }
        return $fallback
    }
    $mysqlPort = Get-ConfigValue "MYSQL_PORT" "13306"
    $redisPort = Get-ConfigValue "REDIS_PORT" "16379"
    $frontendPort = Get-ConfigValue "FRONTEND_PORT" "3000"
    $adminFrontendPort = Get-ConfigValue "ADMIN_FRONTEND_PORT" "3001"
    $backendPort = Get-ConfigValue "BACKEND_PORT" "8080"

    Write-Host "[prod-local] starting root docker-compose.yml ..."
    docker compose up -d --build

    Write-Host ""
    Write-Host "[prod-local] stable local deployment environment"
    Write-Host "  mysql      : localhost:$mysqlPort"
    Write-Host "  redis      : localhost:$redisPort"
    Write-Host "  frontend   : http://localhost:$frontendPort"
    Write-Host "  admin-web  : http://localhost:$adminFrontendPort"
    Write-Host "  backend    : http://localhost:$backendPort"
    Write-Host "  swagger    : http://localhost:$backendPort/swagger-ui/index.html"
    Write-Host ""
    Write-Host "[prod-local] if you need different ports, edit .env before running this script."
    Write-Host "[prod-local] do not run 'docker compose down -v' unless you really want to delete prod-local data."
}
finally {
    Pop-Location
}
