$ErrorActionPreference = "Continue"

$DockerDesktop = "C:\Program Files\Docker\Docker\Docker Desktop.exe"
$LogPath = "C:\ProgramData\LLM\logs\docker-desktop-autostart.log"

function Write-Log {
    param([string]$Message)

    $stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Add-Content -Path $LogPath -Value "[$stamp] $Message"
}

function Test-DockerEngine {
    docker version *> "$env:TEMP\llm-docker-version-check.txt"
    return ($LASTEXITCODE -eq 0)
}

New-Item -ItemType Directory -Force (Split-Path $LogPath) | Out-Null

if (Test-DockerEngine) {
    Write-Log "Docker Engine is already running."
    exit 0
}

Write-Log "Docker Engine is not available; starting Docker Desktop."
Start-Process -FilePath $DockerDesktop -WindowStyle Hidden

for ($i = 1; $i -le 60; $i++) {
    Start-Sleep -Seconds 5
    if (Test-DockerEngine) {
        Write-Log "Docker Engine became available after $($i * 5) seconds."
        exit 0
    }
}

Write-Log "Docker Engine did not become available within timeout."
exit 1
