[CmdletBinding()]
param()

$ErrorActionPreference = 'Continue'
$root = $PSScriptRoot
$logDir = 'D:\Bio-Digital-State\logs'
$stopFile = 'D:\Bio-Digital-State\STOP_DAEMON'

New-Item -ItemType Directory -Path $logDir -Force | Out-Null

Write-Host '[bio-daemon] starting auto-healing Bio-Digital daemon.'
Write-Host "[bio-daemon] create $stopFile to stop after the current cycle."

while (-not (Test-Path -LiteralPath $stopFile)) {
    $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
    $log = Join-Path $logDir "daemon-$stamp.log"
    try {
        Write-Host "[bio-daemon] launching chat+background learn. log=$log"
        & (Join-Path $root 'START_CHAT.ps1') *>&1 | Tee-Object -FilePath $log
        Write-Host '[bio-daemon] Bio-Digital exited; restarting in 5 seconds.'
    } catch {
        Write-Host "[bio-daemon] crash captured: $($_.Exception.Message)"
        Add-Content -LiteralPath $log -Value "[bio-daemon] crash: $($_.Exception.Message)"
    }
    Start-Sleep -Seconds 5
}

Write-Host '[bio-daemon] stop file detected; daemon exiting.'
