$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

function Remove-DirectoryIfExists {
  param(
    [Parameter(Mandatory = $true)]
    [string]$Path
  )

  if (Test-Path -LiteralPath $Path) {
    Write-Host "Removing directory:" $Path
    Remove-Item -LiteralPath $Path -Recurse -Force
  }
}

function Clear-DirectoryContents {
  param(
    [Parameter(Mandatory = $true)]
    [string]$Path
  )

  if (!(Test-Path -LiteralPath $Path)) {
    return
  }

  Write-Host "Clearing directory contents:" $Path
  Get-ChildItem -LiteralPath $Path -Force -ErrorAction SilentlyContinue | ForEach-Object {
    Remove-Item -LiteralPath $_.FullName -Recurse -Force
  }
}

$cacheDirs = Get-ChildItem -Path $root -Directory -Recurse -Force -ErrorAction SilentlyContinue |
  Where-Object { $_.Name -eq "__pycache__" }

foreach ($dir in $cacheDirs) {
  Write-Host "Removing cache directory:" $dir.FullName
  Remove-Item -LiteralPath $dir.FullName -Recurse -Force
}

Remove-DirectoryIfExists -Path (Join-Path $root ".pytest_cache")
Remove-DirectoryIfExists -Path (Join-Path $root ".codex_tmp")
Remove-DirectoryIfExists -Path (Join-Path $root ".local_stack")
Remove-DirectoryIfExists -Path (Join-Path $root ".artifacts")

$dataDirs = Get-ChildItem -Path $root -Directory -Force -ErrorAction SilentlyContinue |
  Where-Object {
    $_.Name -eq ".data" -or
    $_.Name -eq ".data_local" -or
    $_.Name -eq ".data_smoke" -or
    $_.Name -like ".data_gate*" -or
    $_.Name -like ".data_uat_*"
  }

foreach ($dir in $dataDirs) {
  Clear-DirectoryContents -Path $dir.FullName
}

Write-Host ""
Write-Host "Workspace cleanup completed."
Write-Host "Preserved source directories, docs, templates, and backups."
