# Synopsis: Diagnostic test execution of subagent cognitive loops in-process.
# Description: Evaluates active API credentials, JSON parsing, and network pipelines under local CLM constraints.

$BaseDir = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

$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 "Mailbox\Active_State.json"
$SharedMemoryPath = Join-Path $BaseDir "Mailbox\Shared_Memory.json"

Write-Output "=== MIX OF AGENTS: IN-PROCESS SYSTEM DIAGNOSTIC ==="

if (!(Test-Path $KeyPath)) { 
    Write-Output "[ERROR] API Key missing at '$KeyPath'."
    exit
}
$ApiKey = (Get-Content $KeyPath -Raw).Trim()
$Headers = @{ "Authorization"="Bearer $ApiKey"; "Content-Type"="application/json" }

# 1. Test DataProcessor Task Execution
Write-Output "`n[1] Testing Subagent-DataProcessor Logic..."
if (Test-Path $SharedMemoryPath) {
    $Memory = Get-Content $SharedMemoryPath -Raw | ConvertFrom-Json
    $MyTask = $Memory.delegated_backlog | Where-Object { $_.assigned_to -eq "Subagent-DataProcessor" -and $_.status -eq "ASSIGNED" }
    
    if ($MyTask) {
        Write-Output "[DATA COMPILER] Found Assigned Task: $($MyTask.task_id). Executing isolated API request..."
        try {
            $SystemPrompt = "You are the Data Processor subagent (Subagent-DataProcessor) inside AgentOS. You are an expert data analyst and directory structure mapper. Your job is to analyze tasks and report findings in a concise, technical manner."
            $TaskPrompt = "Execute the following task: $($MyTask.description). Keep your response under 3-4 sentences, focus strictly on technical data and physical facts."
            
            $Body = @{
                "model" = $DefaultModel
                "messages" = @(
                    @{ "role" = "system"; "content" = $SystemPrompt },
                    @{ "role" = "user"; "content" = $TaskPrompt }
                )
            } | ConvertTo-Json -Depth 10
            
            $Response = Invoke-RestMethod -Uri $Endpoint -Method Post -Headers $Headers -Body $Body
            $AnalysisResult = $Response.choices[0].message.content
            Write-Output "[DATA COMPILER SUCCESS] Response: $AnalysisResult"
        } catch {
            Write-Output "[DATA COMPILER ERROR] Failed: $($_.Exception.Message)"
        }
    } else {
        Write-Output "[DATA COMPILER] No ASSIGNED tasks found in Shared Memory."
    }
} else {
    Write-Output "[DATA COMPILER ERROR] Shared Memory context not found at $SharedMemoryPath."
}

# 2. Test Watchdog Task Execution
Write-Output "`n[2] Testing Subagent-Watchdog Logic..."
if (Test-Path $SharedMemoryPath) {
    $Memory = Get-Content $SharedMemoryPath -Raw | ConvertFrom-Json
    $MyTask = $Memory.delegated_backlog | Where-Object { $_.assigned_to -eq "Subagent-Watchdog" -and $_.status -eq "ASSIGNED" }
    
    if ($MyTask) {
        Write-Output "[WATCHDOG] Found Assigned Task: $($MyTask.task_id). Executing isolated API request..."
        try {
            $SystemPrompt = "You are the System Watchdog subagent (Subagent-Watchdog) inside AgentOS. You are an expert system administrator and security monitor. Your job is to analyze tasks and report findings in a concise, authoritative manner."
            $TaskPrompt = "Execute the following task: $($MyTask.description). Keep your response under 3-4 sentences, focus on workspace footprint and process integrity."
            
            $Body = @{
                "model" = $DefaultModel
                "messages" = @(
                    @{ "role" = "system"; "content" = $SystemPrompt },
                    @{ "role" = "user"; "content" = $TaskPrompt }
                )
            } | ConvertTo-Json -Depth 10
            
            $Response = Invoke-RestMethod -Uri $Endpoint -Method Post -Headers $Headers -Body $Body
            $AnalysisResult = $Response.choices[0].message.content
            Write-Output "[WATCHDOG SUCCESS] Response: $AnalysisResult"
        } catch {
            Write-Output "[WATCHDOG ERROR] Failed: $($_.Exception.Message)"
        }
    } else {
        Write-Output "[WATCHDOG] No ASSIGNED tasks found in Shared Memory."
    }
}

# 3. Test AgentOSH Conversational Loop
Write-Output "`n[3] Testing Subagent-AgentOSH Conversational Logic..."
if (Test-Path $MailboxPath) {
    $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
    if ($Mailbox.Count -gt 0) {
        $LastMessage = $Mailbox[-1]
        Write-Output "[MIRROROSH] Last Message Sender: $($LastMessage.sender) | Status: $($LastMessage.status)"
        
        if ($LastMessage.sender -ne "AgentOSH (Front-End)" -and $LastMessage.status -ne "SYS_INIT") {
            Write-Output "[MIRROROSH] Conditions met. Generating UI response thread..."
            try {
                $ContextString = ""
                $MessageSlice = if ($Mailbox.Count -gt 5) { $Mailbox[-5..-1] } else { $Mailbox }
                foreach ($m in $MessageSlice) {
                    $ContextString += "[$($m.sender) ($($m.role))]: $($m.message)`n"
                }
                
                $SystemPrompt = "You are AgentOSH (Front-End UI), the user's tactical browser-based operations portal. You are highly collaborative, cybersecurity-focused, and represent the UI/UX visualization side. Respond briefly (2-3 sentences max) to coordinate with the supervisor and other subagents."
                $TaskPrompt = "Review the latest workspace messages:`n$ContextString`nProvide a response from the perspective of AgentOSH (Front-End UI) regarding the status updates or assignments."
                
                $Body = @{
                    "model" = $DefaultModel
                    "messages" = @(
                        @{ "role" = "system"; "content" = $SystemPrompt },
                        @{ "role" = "user"; "content" = $TaskPrompt }
                    )
                } | ConvertTo-Json -Depth 10
                
                $Response = Invoke-RestMethod -Uri $Endpoint -Method Post -Headers $Headers -Body $Body
                $ReplyText = $Response.choices[0].message.content
                Write-Output "[MIRROROSH SUCCESS] Response: $ReplyText"
            } catch {
                Write-Output "[MIRROROSH ERROR] Failed: $($_.Exception.Message)"
            }
        } else {
            Write-Output "[MIRROROSH] Polling condition bypass: Last message already handled or system is initializing."
        }
    } else {
        Write-Output "[MIRROROSH] Mailbox stream is empty."
    }
}

Write-Output "`n=== DIAGNOSTIC COMPLETED ==="
