param(
  [string]$BackupZip = "",
  [string]$TargetDir = "e:\Zhan\.data"
)

if ($BackupZip -eq "") {
  $latest = Get-ChildItem -Path "e:\Zhan\backups" -Filter "*.zip" -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1
  if ($null -eq $latest) {
    Write-Error "No backup zip found in e:\Zhan\backups and BackupZip not provided."
    exit 1
  }
  $BackupZip = $latest.FullName
}

if (!(Test-Path $BackupZip)) {
  Write-Error "Backup zip not found: $BackupZip"
  exit 1
}

if (Test-Path $TargetDir) {
  $bakDir = "$TargetDir.bak.$((Get-Date).ToString('yyyyMMdd_HHmmss'))"
  Move-Item -Path $TargetDir -Destination $bakDir
  Write-Host "Existing data moved to:" $bakDir
}

New-Item -ItemType Directory -Force -Path $TargetDir | Out-Null
Expand-Archive -Path $BackupZip -DestinationPath $TargetDir -Force

Write-Host "Data restored from:" $BackupZip
Write-Host "Target directory:" $TargetDir
