[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$exeName = "bio-chat-$PID.exe"
$bio = Join-Path $root "build\bin\$exeName"
$state = 'D:\Bio-Digital-State\phi3-mini.bdst'
$lock = 'D:\Bio-Digital-State\phi3-mini.lock'
$cap = 1099511627776

function Enter-BioLock {
    if (Test-Path -LiteralPath $lock) {
        $oldPidText = Get-Content -LiteralPath $lock -ErrorAction SilentlyContinue | Select-Object -First 1
        $oldPid = 0
        if ([int]::TryParse($oldPidText, [ref]$oldPid)) {
            $oldProc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
            if ($oldProc) {
                throw "Bio-Digital is already running for this state. PID=$oldPid. Use that window, or stop it before starting chat."
            }
        }
        Remove-Item -LiteralPath $lock -Force -ErrorAction SilentlyContinue
    }
    New-Item -ItemType Directory -Path (Split-Path -Parent $lock) -Force | Out-Null
    Set-Content -LiteralPath $lock -Value $PID -NoNewline
}

function Exit-BioLock {
    $lockPidText = Get-Content -LiteralPath $lock -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($lockPidText -eq "$PID") {
        Remove-Item -LiteralPath $lock -Force -ErrorAction SilentlyContinue
    }
}

if (-not (Test-Path -LiteralPath $state)) {
    & (Join-Path $root 'run_phi3_auto.ps1') -SkipLearn -MaxTokens 8
    if ($LASTEXITCODE -ne 0) { throw 'Bio-Digital ingest failed' }
}

Enter-BioLock
try {
    & (Join-Path $root 'build.ps1') -Config Debug -ExeName $exeName
    if ($LASTEXITCODE -ne 0) { throw 'Bio-Digital chat build failed' }
    & $bio serve $state --profile nrl-daemon --idle-learn-after-sec 60 --checkpoint-sec 15 --max-tokens 128 --cap-bytes $cap
} finally {
    Exit-BioLock
}
