# Crea un ZIP con timestamp en ./backups/ evitando archivos bloqueados:
# Copia el proyecto a %TEMP% (excluye backups/.git/node_modules/vendor) y comprime desde allí.
param()
$ErrorActionPreference = 'Stop'

$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

$ts = Get-Date -Format 'yyyyMMdd-HHmmss'
$backupDir = Join-Path $root 'backups'
if (!(Test-Path $backupDir)) { New-Item -ItemType Directory -Force -Path $backupDir | Out-Null }
$tempDir = Join-Path $env:TEMP ("esp_backup_" + $ts)
if (Test-Path $tempDir) { Remove-Item $tempDir -Recurse -Force }
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null

# Copiar todo excepto carpetas pesadas/irrelevantes (incluimos vendor para el ZIP reducido)
robocopy $root $tempDir /MIR /R:1 /W:1 /XD backups .git node_modules | Out-Null

# Limpiar vendor en la copia temporal (no toca el vendor original)
$vendorTmp = Join-Path $tempDir 'vendor'
if (Test-Path $vendorTmp) {
  Write-Host "Limpiando vendor en copia temporal..."
  $dirsAEliminar = @('tests','test','docs','doc','examples','example','.github','.git','.idea','.vscode')
  foreach ($d in $dirsAEliminar) {
    Get-ChildItem -Path $vendorTmp -Directory -Recurse -Force -ErrorAction SilentlyContinue |
      Where-Object { $_.Name -ieq $d } | ForEach-Object {
        try { Remove-Item $_.FullName -Recurse -Force -ErrorAction Stop } catch {}
      }
  }

  # Archivos comunes innecesarios para runtime
  $patternsArchivos = @(
    '*.md','*.markdown','CHANGELOG*','CHANGES*','CONTRIBUTING*','UPGRADE*','UPGRADING*','CODE_OF_CONDUCT*','phpunit*','phpstan*','psalm*','*.xml','*.dist','*.neon','*.yml','*.yaml','*.editorconfig','.gitattributes','.gitignore','.scrutinizer*','*.yml.dist','*.xml.dist','*.yml.example'
  )
  foreach ($pat in $patternsArchivos) {
    Get-ChildItem -Path $vendorTmp -Recurse -Force -File -Filter $pat -ErrorAction SilentlyContinue |
      Where-Object { $_.Name -notmatch 'LICENSE' } | ForEach-Object {
        try { Remove-Item $_.FullName -Force -ErrorAction Stop } catch {}
      }
  }
}

$dest = Join-Path $backupDir ("esp-" + $ts + ".zip")
Compress-Archive -Path (Join-Path $tempDir '*') -DestinationPath $dest -Force

# Limpiar temporal
Remove-Item $tempDir -Recurse -Force

Write-Host ("Backup creado: " + $dest)
