$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $PSScriptRoot
$outDir = Join-Path $root "resources/converter/win"
$venv = Join-Path $root "scripts/.converter-venv"

$python = Get-Command py -ErrorAction SilentlyContinue
if ($python) {
  & py -3.11 -c "import sys; print(sys.version)" 2>$null
  if ($LASTEXITCODE -ne 0) {
    Write-Host "Python 3.11 is required (py -3.11). Please install it."
    exit 1
  }
  & py -3.11 -m venv $venv
} else {
  Write-Host "Python launcher (py) not found. Please install Python 3.11 and ensure 'py' is available."
  exit 1
}
& "$venv/Scripts/activate.ps1"

pip install --upgrade pip
pip install "TGConvertor[tdata]==0.1.4" telethon pyinstaller

pyinstaller --onefile "$root/scripts/tdata_converter.py" --name tgconvertor --distpath "$root/dist/tdata_converter" --collect-all TGConvertor --collect-all opentele --collect-all telethon

New-Item -ItemType Directory -Force -Path $outDir | Out-Null
Copy-Item -Force "$root/dist/tdata_converter/tgconvertor.exe" (Join-Path $outDir "tgconvertor.exe")

Remove-Item -Recurse -Force "$root/dist/tdata_converter" "$root/build" "$root/tdata_converter.spec"

Write-Host "Converter built: $outDir\tgconvertor.exe"
