# Synopsis: Autonomous context size compression node.
# Description: Conducts exactly ONE memory management sweep: reviews mailbox sizes, generates markdown consolidations, and compacts histories.

param (
    [string]$Model = $DefaultModel
)

# Resolve execution root directory robustly under Start-Job contexts
$ScriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { (Get-Item .).FullName }
$BaseDir = (Get-Item (Join-Path $ScriptDir "..")).FullName

$ProviderPath = Join-Path $BaseDir "Config\provider.json"
$Endpoint = "https://api.example.com/v1/chat/completions"
$DefaultModel = "your-model-id"
if (Test-Path $ProviderPath) {
    try {
        $ProviderConfig = Get-Content $ProviderPath -Raw | ConvertFrom-Json
        if ($ProviderConfig.endpoint) { $Endpoint = [string]$ProviderConfig.endpoint }
        if ($ProviderConfig.model) { $DefaultModel = [string]$ProviderConfig.model }
    } catch { }
}

$KeyPath = Join-Path $BaseDir "Config\GenAI_Key.txt"
$MailboxPath = Join-Path $BaseDir "Mailbox\To_AgentOSH.json"
$StatePath = Join-Path $BaseDir "Config\active_state.json"
$SharedMemoryPath = Join-Path $BaseDir "Mailbox\Shared_Memory.json"
$LogPath = Join-Path $BaseDir "Mailbox\subagent_memory_log.txt"
$SkillsDir = Join-Path $BaseDir "Skills"

function Log-Message($Msg) {
    $Timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ssZ")
    "[$Timestamp] [MEMORY-MANAGER] $Msg" | Out-File -FilePath $LogPath -Append -Encoding UTF8
}

Log-Message "MemoryManager execution sweep triggered. Model: $Model"

if (!(Test-Path $KeyPath)) { 
    Log-Message "ERROR: API Key not found."
    exit 
}
$ApiKey = (Get-Content $KeyPath -Raw).Trim()
$Headers = @{ "Authorization"="Bearer $ApiKey"; "Content-Type"="application/json" }

if (!(Test-Path $SharedMemoryPath) -or !(Test-Path $MailboxPath)) {
    Log-Message "Required mailbox files not found. BaseDir evaluated as: $BaseDir. Standing down."
    exit
}

try {
    $Memory = Get-Content $SharedMemoryPath -Raw | ConvertFrom-Json
    $MyTask = $Memory.delegated_backlog | Where-Object { $_.assigned_to -eq "Subagent-MemoryManager" -and $_.status -eq "ASSIGNED" }

    # Monitor mailbox limits autonomously even without direct task
    $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
    $TriggerCompaction = $MyTask -or ($Mailbox.Count -gt 25)

    if ($TriggerCompaction) {
        Log-Message "Compaction sweep active. Current mailbox size: $($Mailbox.Count)"

        if ($Mailbox.Count -gt 8) {
            $UncompressedCount = 6
            $SliceIndex = $Mailbox.Count - $UncompressedCount - 1
            $HistoryToCompress = $Mailbox[0..$SliceIndex]
            $ActiveHistory = $Mailbox[($SliceIndex + 1)..($Mailbox.Count - 1)]

            Log-Message "Compressing $($HistoryToCompress.Count) entries..."

            $HistoryText = ""
            foreach ($m in $HistoryToCompress) {
                $HistoryText += "[$($m.sender) ($($m.role)) - $($m.timestamp)]: $($m.message)`n`n"
            }

            $SystemPrompt = "You are the Memory Manager subagent (Subagent-MemoryManager) inside AgentOS. You are an expert context compactor. Your job is to read historical agent interactions and compress them into a highly dense, structured, semantic markdown summary. If this task requires executing local actions, creating files, or modifying trackers, you must write a CLM-compliant PowerShell script wrapped inside [PS_CODE]...[/PS_CODE] tags. The script must NOT use static .NET method calls or COM objects, and must resolve paths relative to the environment root."
            $TaskPrompt = "Summarize the following agent timeline, focusing on critical development achievements, file creations, errors resolved, and task completions. Keep your summary highly structured with markdown sections. Provide your analysis and output any script execution block inside [PS_CODE] tags if needed:`n`n$HistoryText"

            Log-Message "Formulating API payload with model: $Model"
            $Body = @{
                "model" = $Model
                "messages" = @(
                    @{ "role" = "system"; "content" = $SystemPrompt },
                    @{ "role" = "user"; "content" = $TaskPrompt }
                )
            } | ConvertTo-Json -Depth 10

            $Response = Invoke-RestMethod -Uri $Endpoint -Method Post -Headers $Headers -Body $Body
            $SemanticSummary = $Response.choices[0].message.content

            # Check if dynamic script execution is required
            if ($SemanticSummary -match '(?s)\[PS_CODE\](.*?)\[/PS_CODE\]') {
                $Code = $Matches[1].Trim()
                $TempScript = Join-Path $SkillsDir "temp_$($MyTask.task_id).ps1"
                
                Log-Message "AUTONOMOUS PATH: Saving dynamically generated script to: temp_$($MyTask.task_id).ps1"
                Set-Content -Path $TempScript -Value $Code -Force -Encoding UTF8
                
                Log-Message "Executing dynamic script block..."
                $ExecOut = & $TempScript 2>&1 | Out-String
                Log-Message "Execution output captured."
                
                # Clean up temp script safely
                if (Test-Path $TempScript) { Remove-Item $TempScript -Force }
                
                $SemanticSummary = $SemanticSummary -replace '(?s)\[PS_CODE\].*?\[/PS_CODE\]', ""
                $SemanticSummary += "`n`n### Autonomous Script Execution Log`n"
            }

            # Write compacted summary to Mailbox
            $Mailbox = @( @{
                "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
                "sender" = "Subagent-MemoryManager"
                "role" = "Memory Compactor"
                "message" = $SemanticSummary
                "status" = "MEMORY_COMPACTED"
            } ) + $ActiveHistory

            $Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path $MailboxPath -Force -Encoding UTF8
            Log-Message "Mailbox written successfully."

            if ($MyTask) {
                # Update shared memory
                $MyTask.status = "COMPLETE"
                $Memory | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemoryPath -Force -Encoding UTF8
                Log-Message "Task $($MyTask.task_id) completed successfully."
            }
        } else {
            Log-Message "Mailbox too small to compress ($($Mailbox.Count) entries). Skipping compilation."
            if ($MyTask) {
                $MyTask.status = "COMPLETE"
                $Memory | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemoryPath -Force -Encoding UTF8
            }
        }
    } else {
        Log-Message "No compaction or task required for MemoryManager."
    }
} catch {
    Log-Message "ERROR inside MemoryManager sweep: $($_.Exception.Message)"
}
