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

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$VendooDir = Split-Path -Parent $ScriptDir
$LogDir = Join-Path $VendooDir 'logs'
$StateFile = Join-Path $LogDir 'local-flux-runtime-state.json'
$PidFile = Join-Path $LogDir 'local-flux-runtime.pid'

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

$items = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object {
  $_.CommandLine -and $_.CommandLine -match 'ComfyUI[\\/]main\.py' -and $_.CommandLine -match '--port\s+8188'
})
foreach ($item in $items) { Stop-Process -Id $item.ProcessId -Force -ErrorAction SilentlyContinue }
Remove-Item -LiteralPath $PidFile -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
$state = [ordered]@{
  status = 'stopped'
  message = 'FLUX / ComfyUI wurde beendet.'
  pid = $null
  port = 8188
  url = 'http://127.0.0.1:8188'
  elapsed_seconds = 0
  updated_at = (Get-Date).ToString('o')
  error = ''
}
Write-Utf8NoBom -Path $StateFile -Content ($state | ConvertTo-Json -Depth 4)
exit 0
