param(
    [string]$InstallDir = "C:\TMarketPOS"
)

$ErrorActionPreference = "Stop"

$vendor = Join-Path $InstallDir "public\vendor"
New-Item -ItemType Directory -Force -Path $vendor | Out-Null

$libraries = @(
    @{ Name="tesseract.min.js"; Url="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js"; MinBytes=40000 },
    @{ Name="worker.min.js"; Url="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/worker.min.js"; MinBytes=80000 },
    @{ Name="xlsx.full.min.js"; Url="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"; MinBytes=700000 },
    @{ Name="jspdf.umd.min.js"; Url="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"; MinBytes=250000 },
    @{ Name="JsBarcode.all.min.js"; Url="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"; MinBytes=40000 },
    @{ Name="lucide.min.js"; Url="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"; MinBytes=200000 }
)

Write-Host "[T Market POS] Descargando librerias locales en: $vendor" -ForegroundColor Cyan

foreach($lib in $libraries) {
    $target = Join-Path $vendor $lib.Name
    try {
        Write-Host " - $($lib.Name)"
        Invoke-WebRequest -Uri $lib.Url -OutFile $target -UseBasicParsing -TimeoutSec 60
        $size = (Get-Item -LiteralPath $target).Length
        if($size -lt $lib.MinBytes) {
            throw "Descarga incompleta: $size bytes"
        }
    } catch {
        Write-Host "   No se pudo descargar $($lib.Name): $($_.Exception.Message)" -ForegroundColor Yellow
        if(Test-Path -LiteralPath $target) {
            Remove-Item -LiteralPath $target -Force -ErrorAction SilentlyContinue
        }
    }
}

Write-Host "[T Market POS] Proceso terminado. Si alguna libreria fallo, el sistema usara internet como respaldo temporal." -ForegroundColor Green
