# amemor.ai - end-to-end Windows installer (WSL2 + Ubuntu + smart-install)
# Focus: GPU/Ollama local models + voice. Run elevated (the .bat does that).
# Re-runnable: if WSL needs enabling it asks for one reboot, then run again.
param(
  [string]$Tiers   = "core,memory,studio",
  [string]$Product = "uaml",
  [string]$Distro  = "Ubuntu-24.04"
)
$ErrorActionPreference = "Stop"
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
function Step($m){ Write-Host ("`n=== " + $m + " ===") -ForegroundColor Cyan }

# 1. WSL2 present?
Step "1/6 Checking WSL2"
$wslOk = $false
try { wsl.exe --status 2>$null | Out-Null; if ($LASTEXITCODE -eq 0) { $wslOk = $true } } catch {}
if (-not $wslOk) {
  Write-Host "WSL2 not enabled - enabling now (this needs ONE reboot)..." -ForegroundColor Yellow
  wsl.exe --install --no-distribution
  Write-Host "" 
  Write-Host "REBOOT WINDOWS, then run this installer again." -ForegroundColor Magenta
  exit 0
}
wsl.exe --set-default-version 2 2>$null | Out-Null

# 2. Ubuntu distro present?
Step "2/6 Ensuring distro $Distro"
$distros = (wsl.exe --list --quiet 2>$null) -join "`n"
if ($distros -notmatch "Ubuntu") {
  Write-Host ("Installing " + $Distro + " (no launch)...")
  wsl.exe --install -d $Distro --no-launch
  Start-Sleep 5
}
wsl.exe -d $Distro -u root -- bash -lc "echo WSL_ROOT_OK; uname -a"
if ($LASTEXITCODE -ne 0) {
  Write-Host ("Ubuntu not ready. Open '" + $Distro + "' once from Start menu to finish setup, then re-run.") -ForegroundColor Yellow
  exit 1
}

# 3. Copy bundle into WSL + run smart-install
Step ("3/6 Running smart-install inside WSL2 (--tiers " + $Tiers + ")")
$bundleWin = Join-Path $here "smart-install.tar.gz"
if (-not (Test-Path $bundleWin)) { throw ("missing " + $bundleWin) }
$drive = ($bundleWin.Substring(0,1)).ToLower()
$bundleWsl = "/mnt/" + $drive + ($bundleWin.Substring(2) -replace '\\','/')
$cmd = "set -e; rm -rf /opt/smart-install; mkdir -p /opt/smart-install; tar xzf '" + $bundleWsl + "' -C /opt/smart-install; cd /opt/smart-install; SMART_INSTALL_DIR=/opt/smart-install ./install.sh --product " + $Product + " --tiers " + $Tiers + " --dumb --accept-eula --no-telemetry 2>&1 | tee /root/amemor-install.log"
wsl.exe -d $Distro -u root -- bash -lc $cmd

# 4. GPU / Ollama check
Step "4/6 GPU + Ollama"
wsl.exe -d $Distro -u root -- bash -lc "command -v nvidia-smi >/dev/null && nvidia-smi --query-gpu=name,memory.total --format=csv,noheader || echo 'WARN: nvidia-smi not in WSL - install the NVIDIA Windows driver (gives CUDA to WSL2)'; echo '--- ollama ---'; command -v ollama >/dev/null && (ollama list 2>/dev/null | head) || echo 'ollama not installed'"

# 5. Voice functional check (local Piper cs, file-based, no audio HW)
Step "5/6 Voice (local TTS smoke test)"
wsl.exe -d $Distro -u root -- bash -lc "V=/opt/voice-onboard/.venv/bin; M=/opt/voice-onboard/voices/piper/cs_CZ-jirka-medium.onnx; if [ -x \$V/piper ] && [ -f \$M ]; then echo 'Ahoj, vitejte v amemor ai.' | \$V/piper --model \$M --output_file /root/voice_test.wav 2>&1 | tail -1; ls -la /root/voice_test.wav && echo 'VOICE LOCAL TTS OK'; else echo 'voice deps/model not present - check /root/amemor-install.log voice steps'; fi"

# 6. Windows host: hosts file + Root CA (browser access to *.amemor-ai.lan)
Step "6/6 Windows host integration (hosts + Root CA)"
$crt = Join-Path $here "uaml-amemor-ai-lan-root.crt"
wsl.exe -d $Distro -u root -- bash -lc "cat /etc/caddy/local-ca/ca.crt 2>/dev/null" | Out-File -Encoding ascii $crt
if ((Test-Path $crt) -and ((Get-Item $crt).Length -gt 0)) {
  & (Join-Path $here "Setup-AmemorAI.ps1")
} else {
  Write-Host "CA cert not produced by install - skipping host trust. Re-run after a successful install." -ForegroundColor Yellow
}
$log = "\\wsl`$\" + $Distro + "\root\amemor-install.log"
Write-Host ""
Write-Host ("DONE. Open Chrome -> https://studio.amemor-ai.lan/   (install log: " + $log + ")") -ForegroundColor Green
