param(
    [int]$TimeoutSeconds = 120
)

Write-Host "Starting docker compose (debug) in detached mode..."
docker compose up --build -d
$composeExit = $LASTEXITCODE

$start = [DateTime]::UtcNow
$containerSeen = $false
while (([DateTime]::UtcNow - $start).TotalSeconds -lt $TimeoutSeconds) {
    $container = docker ps --filter "name=worktracker-dev" --format "{{.Names}}" 2>$null
    if ($container -and $container.Trim() -ne "") {
        if (-not $containerSeen) {
            Write-Host "Found container: $container"
            $containerSeen = $true
        }

        # After container appears, wait a short inner timeout for the app to respond
        $innerStart = [DateTime]::UtcNow
        $innerTimeout = 30
        while (([DateTime]::UtcNow - $innerStart).TotalSeconds -lt $innerTimeout) {
            try {
                $resp = Invoke-WebRequest -UseBasicParsing -Uri http://localhost:8002/ -TimeoutSec 2 -ErrorAction Stop
                if ($resp.StatusCode -ge 200 -and $resp.StatusCode -lt 400) {
                    Write-Host "Application responded (HTTP $($resp.StatusCode)). Ready. Opening browser..."
                    try {
                        Start-Process "http://localhost:8002/"
                    } catch {
                        Write-Host "Failed to open browser: $_"
                    }
                    exit 0
                }
            } catch {
                Start-Sleep -Seconds 1
            }
        }

        Write-Host "Container started but application did not respond within $innerTimeout seconds. Collecting logs..."
        break
    }
    Start-Sleep -Seconds 1
}

Write-Error "Timed out waiting for container or application to become ready after $TimeoutSeconds seconds. Gathering diagnostics..."

Write-Host "-- docker compose ps -- (all services) --"
try {
    docker compose ps
} catch {
    Write-Host "(ps failed): $_"
}

Write-Host "-- docker ps -a (filtered) --"
try {
    docker ps -a --filter "name=worktracker-dev"
} catch {
    Write-Host "(docker ps failed): $_"
}

Write-Host "-- docker compose logs (last 200 lines for service 'worktracker') --"
try {
    docker compose logs --no-color --tail 200 worktracker
} catch {
    Write-Host "(logs failed): $_"
}

if ($composeExit -ne 0) {
    Write-Error "The initial 'docker compose up' returned exit code $composeExit. Check above logs for details."
}

exit 1
