[CmdletBinding()]
param(
    [int]$TimeoutSeconds = 180
)

$ErrorActionPreference = 'Stop'
$Distro = 'MissionCore-CVAT'
$Root = 'D:\NDC_MISSIONCORE'
$RuntimeRoot = Join-Path $Root 'runtime\annotation\cvat'
$LogRoot = Join-Path $RuntimeRoot 'logs'
$LinuxStartScript = '/mnt/d/NDC_MISSIONCORE/workspace/mission-core-compute/cvat/start_cvat_runtime.sh'
$FreeGiBFloor = 360

$drive = Get-PSDrive -Name D
$freeGiB = [math]::Floor($drive.Free / 1GB)
if ($freeGiB -lt $FreeGiBFloor) {
    throw "D: free-space floor crossed ($freeGiB GiB free; $FreeGiBFloor GiB required)"
}

try {
    $about = Invoke-RestMethod -Uri 'http://localhost:8080/api/server/about' -TimeoutSec 3
    if ($about.version -eq '2.70.0') {
        Write-Output "CVAT already ready version=$($about.version) free_gib=$freeGiB"
        exit 0
    }
} catch {
    # A stopped WSL distribution is the normal condition after a Windows reboot.
}

New-Item -ItemType Directory -Path $LogRoot -Force | Out-Null
$timestamp = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ')
$stdoutPath = Join-Path $LogRoot "start-$timestamp.stdout.log"
$stderrPath = Join-Path $LogRoot "start-$timestamp.stderr.log"
$arguments = @(
    '-d', $Distro,
    '-u', 'root',
    '--', 'bash', $LinuxStartScript, '--keepalive'
)

Start-Process -FilePath 'wsl.exe' -ArgumentList $arguments -WindowStyle Hidden `
    -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath

$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
do {
    Start-Sleep -Seconds 2
    try {
        $about = Invoke-RestMethod -Uri 'http://localhost:8080/api/server/about' -TimeoutSec 3
        if ($about.version -eq '2.70.0') {
            Write-Output "CVAT ready version=$($about.version) free_gib=$freeGiB"
            Write-Output "startup_log=$stdoutPath"
            exit 0
        }
    } catch {
        # Continue until the complete CVAT Compose topology is ready.
    }
} while ((Get-Date) -lt $deadline)

throw "CVAT did not become ready within $TimeoutSeconds seconds; inspect $stderrPath"
