[CmdletBinding()]
param(
    [string]$ModelPath = 'C:\Users\Asus\Desktop\Documents\RomaPy Engine\phi-3-mini-4k-instruct.Q4_K_M.gguf',
    [string]$WorkDir = 'D:\Bio-Digital-State',
    [string]$StatePath = '',
    [string]$DeltaPath = '',
    [double]$LearnHours = 12,
    [int]$CheckpointSec = 60,
    [ValidateSet('nrl-daemon','hybrid','nrl-fast','nrl-max','nrl-edge','nrl-sweet','nrl-100k','cpu-quality')]
    [string]$LearnProfile = 'nrl-daemon',
    # Per-run virtual neural steps to add. Existing .bdl progress does not cause an instant skip.
    [UInt64]$TargetSteps = 0,
    # Real disk cap for .bdl + .bdl.pages. Default is 1 TiB.
    [UInt64]$CapBytes = 1099511627776,
    [string]$Prompt = 'hi',
    [int]$MaxTokens = 128,
    [int]$IdleLearnAfterSec = 60,
    [switch]$SkipLearn,
    [switch]$Serve,
    [switch]$ForceReingest
)

$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$bio = Join-Path $root 'build\bin\bio.exe'

function Ensure-Directory {
    param([string]$Path)
    if ([string]::IsNullOrWhiteSpace($Path)) {
        return
    }
    if (Test-Path -LiteralPath $Path) {
        return
    }
    New-Item -ItemType Directory -Path $Path -Force | Out-Null
}

function Assert-DriveAvailable {
    param([string]$Path)
    $qualifier = Split-Path -Qualifier $Path
    if ($qualifier -and -not (Test-Path -LiteralPath $qualifier)) {
        throw "Required drive is not available: $qualifier"
    }
}

if (-not (Test-Path $bio)) {
    Write-Host '[bio-auto] bio.exe missing; building native Bio-Digital...' -ForegroundColor Cyan
    & (Join-Path $root 'build.ps1') -Config Release
    if ($LASTEXITCODE -ne 0) {
        throw 'Bio-Digital build failed'
    }
}

if (-not (Test-Path $ModelPath)) {
    throw "Model not found: $ModelPath"
}

if ([string]::IsNullOrWhiteSpace($StatePath)) {
    $StatePath = Join-Path $WorkDir 'phi3-mini.bdst'
}
if ([string]::IsNullOrWhiteSpace($DeltaPath)) {
    $DeltaPath = Join-Path $WorkDir 'phi3-mini.bdl'
}

Assert-DriveAvailable -Path $WorkDir
Assert-DriveAvailable -Path $StatePath
Assert-DriveAvailable -Path $DeltaPath
Ensure-Directory -Path $WorkDir

$stateDir = Split-Path -Parent $StatePath
$deltaDir = Split-Path -Parent $DeltaPath
Ensure-Directory -Path $stateDir
Ensure-Directory -Path $deltaDir

if ((Test-Path -LiteralPath $StatePath) -and (Test-Path -LiteralPath $DeltaPath) -and -not $ForceReingest) {
    Write-Host '[bio-auto] existing Bio-Digital state found; resuming instead of re-ingesting.' -ForegroundColor Green
} else {
    if ($ForceReingest -and (Test-Path -LiteralPath $DeltaPath)) {
        $backup = "$DeltaPath.bak-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
        Copy-Item -LiteralPath $DeltaPath -Destination $backup -Force
        Write-Host "[bio-auto] backed up existing delta before reingest: $backup" -ForegroundColor Yellow
    }

    Write-Host '[bio-auto] ingesting GGUF into Bio-Digital state on D:...' -ForegroundColor Cyan
    & $bio ingest $ModelPath --out $StatePath --delta $DeltaPath
    if ($LASTEXITCODE -ne 0) {
        throw 'Bio-Digital ingest failed'
    }
}

if (-not $SkipLearn) {
    $learnSeconds = [int][Math]::Max(1, [Math]::Round($LearnHours * 3600))
    Write-Host "[bio-auto] learning on D: for $LearnHours hour(s), checkpoint every $CheckpointSec second(s), profile=$LearnProfile, cap=$CapBytes bytes..." -ForegroundColor Cyan
    Write-Host '[bio-auto] learning pages grow on D: until cap, then prune/quality mode starts.' -ForegroundColor Cyan
    Write-Host '[bio-auto] safe to stop with Ctrl+C; rerun this script to resume from the last checkpoint.' -ForegroundColor Yellow
    if ($TargetSteps -gt 0) {
        Write-Host "[bio-auto] target is additional virtual steps this run: $TargetSteps" -ForegroundColor Cyan
        & $bio learn $StatePath --seconds $learnSeconds --checkpoint-sec $CheckpointSec --profile $LearnProfile --target-steps $TargetSteps --cap-bytes $CapBytes
    } else {
        & $bio learn $StatePath --seconds $learnSeconds --checkpoint-sec $CheckpointSec --profile $LearnProfile --cap-bytes $CapBytes
    }
    if ($LASTEXITCODE -ne 0) {
        throw 'Bio-Digital learn failed. If D: was disconnected, reconnect it and rerun this script to resume from the last checkpoint.'
    }
} else {
    Write-Host '[bio-auto] skipping dedicated learn pass; chat idle-learn remains enabled.' -ForegroundColor Yellow
}

if ($Serve) {
    Write-Host '[bio-auto] starting native Bio-Digital serve loop...' -ForegroundColor Cyan
    & $bio serve $StatePath --max-tokens $MaxTokens --idle-learn-after-sec $IdleLearnAfterSec --checkpoint-sec $CheckpointSec --profile $LearnProfile --cap-bytes $CapBytes
    if ($LASTEXITCODE -ne 0) {
        throw 'Bio-Digital serve failed'
    }
} else {
    Write-Host '[bio-auto] starting native Bio-Digital chat...' -ForegroundColor Cyan
    & $bio chat $StatePath --prompt $Prompt --max-tokens $MaxTokens --idle-learn-after-sec $IdleLearnAfterSec
    if ($LASTEXITCODE -ne 0) {
        throw 'Bio-Digital chat failed'
    }
}

Write-Host '[bio-auto] done.' -ForegroundColor Green
Write-Host "  state: $StatePath"
Write-Host "  delta: $DeltaPath"
