$ErrorActionPreference = "Stop"

function Write-Ok($Text) {
    Write-Host "[OK] $Text" -ForegroundColor Green
}

$TargetFolder = Join-Path $env:USERPROFILE "Documents\AI-Voice-Bridge"
$VenvPython = Join-Path $TargetFolder ".venv\Scripts\python.exe"
$ModelName = "base.en"
$ModelRoot = Join-Path $TargetFolder "whisper-models"

if (-not (Test-Path (Join-Path $TargetFolder "ai_voice_bridge_server.py"))) {
    throw "Main AI Voice Bridge app is not installed in Documents yet. Run Run-AI-Voice-Bridge-Windows-Installer.bat first."
}

if (-not (Test-Path $VenvPython)) {
    throw "Local Python environment was not found: $VenvPython"
}

Write-Host "Model: $ModelName"
Write-Host "Model cache folder: $ModelRoot"
Write-Host "This may download the model the first time. After setup, dictation runs locally."

if (-not (Test-Path $ModelRoot)) {
    New-Item -ItemType Directory -Path $ModelRoot | Out-Null
}

$Code = @"
from faster_whisper import WhisperModel
WhisperModel(r'$ModelName', device='cpu', compute_type='int8', download_root=r'$ModelRoot')
"@

$TempPy = Join-Path $env:TEMP ("rits_whisper_model_check_" + [guid]::NewGuid().ToString("N") + ".py")
Set-Content -Path $TempPy -Value $Code -Encoding UTF8
try {
    & $VenvPython $TempPy
    if ($LASTEXITCODE -ne 0) {
        throw "Whisper model check/download failed."
    }
} finally {
    if (Test-Path $TempPy) { Remove-Item -Force $TempPy }
}

Write-Ok "Whisper model ready."
exit 0
