param(
    [Parameter(Mandatory=$true)][string]$ZipFile,     # Ruta del .zip descargado
    [Parameter(Mandatory=$true)][string]$TargetDir,   # Carpeta del programa instalado
    [Parameter(Mandatory=$true)][string]$ExeFile      # (compatibilidad, no usado)
)

Add-Type -AssemblyName System.IO.Compression.FileSystem

function Log($msg) {
    Write-Host ("[{0}] {1}" -f (Get-Date -Format "HH:mm:ss"), $msg)
}

function Get-ExeVersion($path) {
    try {
        return (Get-Item $path).VersionInfo.ProductVersion
    }
    catch {
        return $null
    }
}

# === Nombre fijo del ejecutable ===
$exeName = "localizzacion.exe"

# === Paths ===
$TempExtract = Join-Path ([System.IO.Path]::GetTempPath()) "Localizacion_extract"
if (Test-Path $TempExtract) { Remove-Item $TempExtract -Recurse -Force }
New-Item -Path $TempExtract -ItemType Directory | Out-Null

# === Extraer ZIP ===
Log "Extrayendo $ZipFile a $TempExtract"
[System.IO.Compression.ZipFile]::ExtractToDirectory($ZipFile, $TempExtract)

# === Comparar versiones ===
$localExe = Join-Path $TargetDir $exeName
$remoteExe = Join-Path $TempExtract $exeName

$localVer = Get-ExeVersion $localExe
$remoteVer = Get-ExeVersion $remoteExe
$needsUpdate = $true

if ($localVer -and $remoteVer) {
    Log "Versión local:  $localVer"
    Log "Versión remota: $remoteVer"
    try {
        if ([Version]$remoteVer -le [Version]$localVer) {
            $needsUpdate = $false
        }
    } catch {
        if ($remoteVer -eq $localVer) { $needsUpdate = $false }
    }
}

# === Leer parámetros externos (params.txt) ===
$paramsFile = Join-Path ([System.IO.Path]::GetTempPath()) "Localizacion_update\params.txt"
$params = ""
if (Test-Path $paramsFile) {
    $params = Get-Content $paramsFile -Raw
    Log "Parámetros encontrados: $params"
}

# === Si NO requiere update ===
if (-not $needsUpdate) {
    Log "Ya tenés la última versión instalada."
    exit 0
}

# === Cerrar proceso viejo ===
$procName = [System.IO.Path]::GetFileNameWithoutExtension($exeName)
$procs = Get-Process -Name $procName -ErrorAction SilentlyContinue
foreach ($p in $procs) {
    try {
        Log "Cerrando proceso $($p.Id) $($p.ProcessName)"
        $p.CloseMainWindow() | Out-Null
        Start-Sleep -Seconds 2
        if (-not $p.HasExited) { $p.Kill() }
    } catch {
        Log "No se pudo cerrar proceso: $($_.Exception.Message)"
    }
}

# === Reemplazar archivos ===
Log "Reemplazando archivos en $TargetDir"
Copy-Item -Path (Join-Path $TempExtract "*") -Destination $TargetDir -Recurse -Force

# === Relanzar aplicación ===
$localExe = Join-Path $TargetDir $exeName
Log "Iniciando $localExe $params"
if ($params -and $params.Trim() -ne "") {
    Start-Process -FilePath $localExe -ArgumentList $params
} else {
    Start-Process -FilePath $localExe
}

Log "Actualización completada."
