# Synopsis: Master Orchestrator Controller & Autonomous Supervisor Step.
# Description: Performs mailbox analysis, updates state, tracks PIDs safely under CLM, and autonomously delegates tasks to backlog.

$BaseDir = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$MailboxPath = Join-Path $BaseDir "Mailbox\To_AgentOSH.json"
$StatePath = Join-Path $BaseDir "Mailbox\Active_State.json"
$SharedMemoryPath = Join-Path $BaseDir "Mailbox\Shared_Memory.json"
$PidFile = Join-Path $BaseDir "Config\subagent_pids.json"

Write-Output "=== MIX OF AGENTS: RUNNING AUTONOMOUS SUPERVISOR STEP ==="

# 1. Update State Timestamp and Execution Loops
if (Test-Path $StatePath) {
    $State = Get-Content $StatePath -Raw | ConvertFrom-Json
    $State.loop_count++
    $State.last_update = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
    
    # Audit subagents PIDs dynamically to register accurate status
    if (Test-Path $PidFile) {
        $Pids = Get-Content $PidFile -Raw | ConvertFrom-Json
        $ActiveCount = 0
        foreach ($agent in $State.agents) {
            # Map PIDs to subagents safely without overwriting the $PID read-only variable
            $subAgentPid = $null
            if ($agent.name -eq "Subagent-DataProcessor") { $subAgentPid = $Pids[0] }
            elseif ($agent.name -eq "Subagent-Watchdog") { $subAgentPid = $Pids[1] }
            elseif ($agent.name -eq "AgentOSH (Front-End)" -or $agent.name -eq "AgentOSH") { $subAgentPid = $Pids[2] }
            elseif ($agent.name -eq "Subagent-MemoryManager") { $subAgentPid = $Pids[3] }
            elseif ($agent.name -eq "Subagent-Supervisor") { $subAgentPid = $Pids[4] }

            if ($subAgentPid -and (Get-Process -Id $subAgentPid -ErrorAction SilentlyContinue)) {
                $agent.status = "ONLINE"
                $ActiveCount++
            } else {
                $agent.status = "OFFLINE"
            }
        }
        
        # Verify if Supervisor is missing from State agents array and register it dynamically
        $SupReg = $State.agents | Where-Object { $_.name -eq "Subagent-Supervisor" }
        if (!$SupReg) {
            $State.agents += @{
                "name" = "Subagent-Supervisor"
                "role" = "Supervisor Brain & Dynamic Task Delegator"
                "status" = "ONLINE"
                "last_active" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
            }
            $ActiveCount++
        }
        
        Write-Output "Active running subagent background processes detected: $ActiveCount/5"
    }
    
    $State | ConvertTo-Json -Depth 10 | Set-Content -Path $StatePath -Force -Encoding UTF8
    Write-Output "State Loop Count incremented to: $($State.loop_count)"
}

# 2. Read Shared Memory Context & Delegate Autonomous Tasks
if (Test-Path $SharedMemoryPath) {
    $Shared = Get-Content $SharedMemoryPath -Raw | ConvertFrom-Json
    
    # Scan backlog tasks
    $ActiveTasks = $Shared.delegated_backlog | Where-Object { $_.status -eq "ASSIGNED" }
    
    if (!$ActiveTasks) {
        Write-Output "All current backlog tasks are COMPLETE. Initiating autonomous supervisor optimization planning..."
        
        # Scenario 1: Reconciled tasks complete. Check if the Temp folder clean task is needed
        $CleanTask = $Shared.delegated_backlog | Where-Object { $_.task_id -eq "TASK-SAN-01" }
        if (!$CleanTask) {
            Write-Output "Supervisor Action: Watchdog environmental audit completed. Delegating physical sanitation task..."
            $NewTask = @{
                "task_id" = "TASK-SAN-01"
                "assigned_to" = "Subagent-Watchdog"
                "description" = "Execute the compiled sanitation skill 'Skills\Optimize-MoAEnvironment.ps1' autonomously to purge temp folders and orphaned Edge processes."
                "status" = "ASSIGNED"
            }
            $Shared.delegated_backlog += $NewTask
            
            $CoordRecord = @{
                "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
                "sender" = "Gemini Enterprise"
                "target" = "Subagent-Watchdog"
                "message" = "Delegated environmental cleanup task TASK-SAN-01 to Subagent-Watchdog based on baseline diagnostics."
            }
            $Shared.neural_bus.coordination_channel += $CoordRecord
            
            $Shared | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemoryPath -Force -Encoding UTF8
            Write-Output "[AUTONOMOUS DELEGATION SUCCESS] TASK-SAN-01 assigned to Watchdog."
        } else {
            # Scenario 2: If everything is 100% synchronized and cleaned up, assign a verification cycle
            $VerifyTask = $Shared.delegated_backlog | Where-Object { $_.task_id -eq "TASK-VERIFY-01" }
            if (!$VerifyTask) {
                Write-Output "Supervisor Action: All tasks complete. Delegating final systems verification cycle..."
                $NewTask = @{
                    "task_id" = "TASK-VERIFY-01"
                    "assigned_to" = "Subagent-DataProcessor"
                    "description" = "Conduct final review of the upgraded deliverables and confirm alignment between Project_Task_Tracker.csv and workspace status."
                    "status" = "ASSIGNED"
                }
                $Shared.delegated_backlog += $NewTask
                
                $CoordRecord = @{
                    "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
                    "sender" = "Gemini Enterprise"
                    "target" = "Subagent-DataProcessor"
                    "message" = "Delegated final verification task TASK-VERIFY-01 to Subagent-DataProcessor."
                }
                $Shared.neural_bus.coordination_channel += $CoordRecord
                
                $Shared | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemoryPath -Force -Encoding UTF8
                Write-Output "[AUTONOMOUS DELEGATION SUCCESS] TASK-VERIFY-01 assigned to DataProcessor."
            } else {
                Write-Output "Ecosystem fully synchronized, cleaned, and verified."
            }
        }
    } else {
        Write-Output "Background subagents currently processing active tasks: $($ActiveTasks.task_id -join ', ')"
    }
}

Write-Output "=== WORKSPACE STEP COMPLETED ==="
