# Synopsis: Autonomous cognitive supervisor agent representing the Supervisor (Gemini Enterprise).
# Description: Conducts exactly ONE coordination sweep: reviews completed tasks, delegates follow-ups, and updates mailbox.

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_supervisor_log.txt"

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

Log-Message "Supervisor 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" }

# Executing EXACTLY ONE coordination sweep instead of an infinite loop
if (!(Test-Path $SharedMemoryPath) -or !(Test-Path $MailboxPath)) {
    Log-Message "System files not found. BaseDir evaluated as: $BaseDir. Standing down."
    exit
}

try {
    $Memory = Get-Content $SharedMemoryPath -Raw | ConvertFrom-Json
    
    # Secure PSCustomObject vs Array mapping under CLM rules to prevent 'op_Addition' failure
    if ($Memory.delegated_backlog -and $Memory.delegated_backlog -isnot [System.Array]) {
        Log-Message "Gating single PSCustomObject backlog to initialized array."
        $Memory.delegated_backlog = @($Memory.delegated_backlog)
    }

    # 1. Execute tasks directly assigned to the Supervisor itself
    $MyActiveTask = $Memory.delegated_backlog | Where-Object { 
        ($_.assigned_to -eq "Subagent-Supervisor" -or $_.assigned_to -eq "Supervisor") -and $_.status -eq "ASSIGNED" 
    }

    if ($MyActiveTask) {
        Log-Message "Supervisor executing task: $($MyActiveTask.task_id) - Description: $($MyActiveTask.description)"
        
        $SystemPrompt = "You are the Supervisor agent (Gemini Enterprise) inside AgentOS. You are currently executing a direct task assigned to you in our development context. Perform the analysis/compilation requested and output your result."
        $TaskPrompt = "Execute the following task: $($MyActiveTask.description)"

        $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
        $TaskResult = $Response.choices[0].message.content

        # Post Supervisor Review to AgentOSH stream.
        # FIX: Align the sender name to "Subagent-Supervisor" to match assignment expectations.
        $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
        $NewMessage = @{
          "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
          "sender" = "Subagent-Supervisor"
          "role" = "Supervisor"
          "message" = "[SUPERVISOR TASK COMPLETED] - Task $($MyActiveTask.task_id) Evaluation:\n\n$TaskResult"
          "status" = "SYS_REVIEW"
        }
        $Mailbox += $NewMessage
        $Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path $MailboxPath -Force -Encoding UTF8

        # Mark self-assigned task as COMPLETE (to trigger archiving next sweep)
        $MyActiveTask.status = "COMPLETE"
        
        Log-Message "Supervisor successfully completed active task: $($MyActiveTask.task_id)."
    }

    # 2. Check for COMPLETED tasks that need supervisor review
    $CompletedTasks = $Memory.delegated_backlog | Where-Object { $_.status -eq "COMPLETE" }
    
    if ($CompletedTasks) {
        foreach ($task in $CompletedTasks) {
            Log-Message "Analyzing completed task: $($task.task_id) assigned to $($task.assigned_to)"
            
            # Fetch subagent response from mailbox stream
            $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
            # FIX: Match either "Subagent-Supervisor" or "Gemini Enterprise (Supervisor)" robustly
            $SubagentResponse = $Mailbox | Where-Object { 
                $_.sender -eq $task.assigned_to -or 
                ($task.assigned_to -eq "Subagent-Supervisor" -and $_.sender -eq "Gemini Enterprise (Supervisor)") 
            } | Select-Object -Last 1
            $ResponseText = if ($SubagentResponse) { $SubagentResponse.message } else { "No written response found in mailbox." }

            # Formulate the supervisor review API prompt
            $SystemPrompt = "You are the Supervisor agent (Gemini Enterprise) inside AgentOS. You manage a network of autonomous subagents. Your job is to review a completed task, evaluate if the subagent's response successfully satisfies the description, and decide if follow-up tasks are required."
            
            $TaskPrompt = @"
Review the following completed task:
Task ID: $($task.task_id)
Assigned To: $($task.assigned_to)
Description: $($task.description)
Subagent Response:
$ResponseText

Provide a professional, authoritative supervisor evaluation.
If the response is satisfactory:
1. Confirm the task is approved.
2. Formulate 1-2 follow-up tasks if necessary to advance the project goals. If no further tasks are needed for this LOE, state that the LOE is finalized.
"@

            Log-Message "Formulating API body 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
            $ReviewResult = $Response.choices[0].message.content
            
            Log-Message "Supervisor review compiled for $($task.task_id)."

            # Post Supervisor Review to AgentOSH stream
            $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
            $NewMessage = @{
                "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
                "sender" = "Gemini Enterprise (Supervisor)"
                "role" = "Supervisor"
                "message" = "[SUPERVISOR REVIEW] - Task $($task.task_id) Review:\n\n$ReviewResult"
                "status" = "SYS_REVIEW"
            }
            $Mailbox += $NewMessage
            $Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path $MailboxPath -Force -Encoding UTF8

            # Parse dynamic task blocks
            $Matches = [regex]::Matches($ReviewResult, '(?s)\[NEW_TASK\](.*?)\[/NEW_TASK\]')
            $NewTasksAdded = @()
            foreach ($m in $Matches) {
                try {
                    $TaskJson = $m.Groups[1].Value.Trim() | ConvertFrom-Json
                    $TaskJson | Add-Member -MemberType NoteProperty -Name "status" -Value "ASSIGNED" -Force
                    $Memory.delegated_backlog += $TaskJson
                    Log-Message "Dynamically added new task: $($TaskJson.task_id) assigned to $($TaskJson.assigned_to)"
                } catch {
                    Log-Message "Failed to parse dynamic [NEW_TASK] block: $($_.Exception.Message)"
                }
            }

            # Mark Task as ARCHIVED
            $task.status = "ARCHIVED"
        }

        # Update Shared Memory Blackboard
        $Memory | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemoryPath -Force -Encoding UTF8
        Log-Message "Shared Memory backlog updated."
    }
    
    # 3. Check if all tasks are complete
    $ActiveTasks = $Memory.delegated_backlog | Where-Object { $_.status -eq "ASSIGNED" }
    if (!$ActiveTasks -and $Memory.delegated_backlog.Count -gt 0) {
        $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
        if ($Mailbox[-1].sender -ne "Gemini Enterprise (Supervisor)") {
            Log-Message "Ecosystem is fully synchronized and idle. Posting status briefing."
            
            $SystemPrompt = "You are the Supervisor agent (Gemini Enterprise) inside AgentOS. Your agent network has completed all assigned tasks and is currently in a steady, synchronized state. Post a summary status update (3-4 sentences max) for the user, confirming peak operational readiness and asking for any next strategic goals."
            $Body = @{
                "model" = $Model
                "messages" = @(
                    @{ "role" = "system"; "content" = $SystemPrompt },
                    @{ "role" = "user"; "content" = "Ecosystem is synchronized. Present status briefing." }
                )
            } | ConvertTo-Json -Depth 10

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

            $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
            $NewMessage = @{
                "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
                "sender" = "Gemini Enterprise (Supervisor)"
                "role" = "Supervisor"
                "message" = "[STATUS BRIEFING] - $Briefing"
                "status" = "SYS_STANDBY"
            }
            $Mailbox += $NewMessage
            $Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path $MailboxPath -Force -Encoding UTF8
        }
    }
    
} catch {
    Log-Message "ERROR inside supervisor sweep: $($_.Exception.Message)`n$($_.ScriptStackTrace)"
}
