param(
  [switch]$NonInteractive,
  [switch]$RemoveDownloads
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 2.0

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$VendooDir = Split-Path -Parent $ScriptDir
$LocalAiDir = Join-Path $VendooDir 'local-ai'
$ComfyRoot = Join-Path $LocalAiDir 'comfyui'
$ExtractTemp = Join-Path $LocalAiDir 'extract-temp'
$Downloads = Join-Path $LocalAiDir 'downloads'
$StateFile = Join-Path $LocalAiDir 'install-state.json'
$StartScript = Join-Path $LocalAiDir 'start-local-flux.ps1'
$StopScript = Join-Path $LocalAiDir 'stop-local-flux.ps1'
$TaskName = 'Vendoo Local FLUX'
$LogDir = Join-Path $VendooDir 'logs'
$LogFile = Join-Path $LogDir 'local-flux-uninstall.log'

New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
New-Item -ItemType Directory -Force -Path $LocalAiDir | Out-Null

function Write-Log([string]$Message, [string]$Level = 'INFO') {
  $line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') [$Level] $Message"
  Add-Content -LiteralPath $LogFile -Value $line -Encoding UTF8
}

function Write-Utf8NoBom([string]$Path, [string]$Content) {
  $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
  [System.IO.File]::WriteAllText($Path, $Content, $utf8NoBom)
}

try {
  Write-Log 'Deinstallation von lokalem FLUX wurde gestartet.'

  if (Test-Path -LiteralPath $StopScript) {
    try {
      & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $StopScript | Out-Null
      Write-Log 'Vorhandenes Stoppskript wurde ausgeführt.' 'OK'
    } catch {
      Write-Log "Stoppskript meldete: $($_.Exception.Message)" 'WARN'
    }
  }

  try {
    $processes = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object {
      $_.CommandLine -match 'ComfyUI\\main.py' -or
      ($_.CommandLine -match [regex]::Escape($VendooDir) -and $_.CommandLine -match 'python_embeded\\python.exe')
    })
    foreach ($process in $processes) {
      Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue
    }
    if ($processes.Count -gt 0) { Write-Log "$($processes.Count) ComfyUI-Prozess(e) beendet." 'OK' }
  } catch {
    Write-Log "Prozessbereinigung meldete: $($_.Exception.Message)" 'WARN'
  }

  Start-Sleep -Seconds 2
  & schtasks.exe /Delete /TN $TaskName /F 2>$null | Out-Null
  Write-Log 'Autostart-Aufgabe wurde entfernt oder war nicht vorhanden.' 'OK'

  if (Test-Path -LiteralPath $ComfyRoot) {
    Remove-Item -LiteralPath $ComfyRoot -Recurse -Force
    Write-Log 'ComfyUI und FLUX-Modell wurden entfernt.' 'OK'
  }
  if (Test-Path -LiteralPath $ExtractTemp) {
    Remove-Item -LiteralPath $ExtractTemp -Recurse -Force
    Write-Log 'Temporäre Entpackdaten wurden entfernt.' 'OK'
  }
  foreach ($path in @($StartScript, $StopScript)) {
    if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force }
  }
  if ($RemoveDownloads -and (Test-Path -LiteralPath $Downloads)) {
    Remove-Item -LiteralPath $Downloads -Recurse -Force
    Write-Log 'Installationsarchive und Teildownloads wurden entfernt.' 'OK'
  } else {
    Write-Log 'Installationsarchive bleiben für eine schnelle Neuinstallation erhalten.' 'INFO'
  }

  $state = [ordered]@{
    status = 'not-started'
    phase = 'uninstalled'
    progress = 0
    message = 'Lokales FLUX wurde deinstalliert.'
    started_at = $null
    updated_at = (Get-Date).ToString('o')
    heartbeat_at = (Get-Date).ToString('o')
    process_id = $PID
    elapsed_seconds = 0
    can_resume = $false
    model_installed = $false
    comfy_installed = $false
  }
  Write-Utf8NoBom -Path $StateFile -Content ($state | ConvertTo-Json -Depth 4)
  Write-Log 'Deinstallation erfolgreich abgeschlossen.' 'OK'
  exit 0
} catch {
  Write-Log $_.Exception.Message 'ERROR'
  try {
    $failed = [ordered]@{
      status = 'failed'
      phase = 'error'
      progress = 0
      message = "Deinstallation fehlgeschlagen: $($_.Exception.Message)"
      updated_at = (Get-Date).ToString('o')
      heartbeat_at = (Get-Date).ToString('o')
      process_id = $PID
    }
    Write-Utf8NoBom -Path $StateFile -Content ($failed | ConvertTo-Json -Depth 4)
  } catch {}
  exit 1
}
