$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $PSScriptRoot
$CommonTesseract = 'C:\Program Files\Tesseract-OCR\tesseract.exe'
$TesseractCommand = Get-Command tesseract -ErrorAction SilentlyContinue
$TesseractPath = if ($TesseractCommand) { $TesseractCommand.Source } elseif (Test-Path $CommonTesseract) { $CommonTesseract } else { $null }
if (!$TesseractPath) {
  $Winget = Get-Command winget -ErrorAction SilentlyContinue
  if (!$Winget) {
    Write-Error 'Tesseract is missing and winget is unavailable. Install UB-Mannheim.TesseractOCR manually, then rerun this script.'
  }
  winget install --id UB-Mannheim.TesseractOCR --accept-package-agreements --accept-source-agreements
  $TesseractCommand = Get-Command tesseract -ErrorAction SilentlyContinue
  $TesseractPath = if ($TesseractCommand) { $TesseractCommand.Source } elseif (Test-Path $CommonTesseract) { $CommonTesseract } else { $null }
}
if (!$TesseractPath) {
  Write-Error 'Tesseract command is still unavailable after installation. Restart the terminal or add Tesseract to PATH.'
}
$Tessdata = Join-Path $Root 'tools\tessdata'
New-Item -ItemType Directory -Force -Path $Tessdata | Out-Null
$Vie = Join-Path $Tessdata 'vie.traineddata'
if (!(Test-Path $Vie)) {
  Invoke-WebRequest -Uri 'https://github.com/tesseract-ocr/tessdata/raw/main/vie.traineddata' -OutFile $Vie
}
$env:TESSDATA_PREFIX = $Tessdata
$Langs = & $TesseractPath --list-langs 2>$null
if ($Langs -notcontains 'vie') {
  Write-Error 'Tesseract is installed, but Vietnamese language data "vie" is missing.'
}
Write-Host "Tesseract with Vietnamese language data is available: $TesseractPath"
