# Synopsis: Dynamic agent and skill provisioning engine for Mixture of Agents (MoA).
# Description: This skill allows the ecosystem to dynamically register new specialized subagent threads 
# (e.g. specialized CSV parsers, HTML scrapers, coding agents) under CLM-compliant execution rules.

[CmdletBinding()]
param (
    [string]$AgentName,
    [string]$RoleDescription,
    [string]$TaskSystemPrompt,
    [string]$TaskQuery,
    [bool]$LaunchAsBackgroundThread = $true
)

$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 { }
}
$SkillsDir = Join-Path $BaseDir "Skills"
$ConfigDir = Join-Path $BaseDir "Config"
$MailboxDir = Join-Path $BaseDir "Mailbox"
$SharedMemPath = Join-Path $MailboxDir "Shared_Memory.json"
$StatePath = Join-Path $BaseDir "Config\active_state.json"

Write-Output "=== MIX OF AGENTS: REGISTERING DYNAMIC PLUGIN ==="

if ([string]::IsNullOrEmpty($AgentName) -or [string]::IsNullOrEmpty($RoleDescription)) {
    Write-Output "[ERROR] AgentName and RoleDescription cannot be null."
    exit
}

# 1. Update Blackboard Capabilities
if (Test-Path $SharedMemPath) {
    $Shared = Get-Content $SharedMemPath -Raw | ConvertFrom-Json
    
    # Check if agent already exists
    if ($Shared.neural_bus.agent_capabilities.$AgentName) {
        Write-Output "Node '$AgentName' already registered in Blackboard. Updating role description..."
    }
    
    # Dynamically inject capability
    $Shared.neural_bus.agent_capabilities | Add-Member -MemberType NoteProperty -Name $AgentName -Value $RoleDescription -Force
    
    # Log delegation record
    $CoordRecord = @{
        "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
        "sender" = "Gemini Enterprise";
        "target" = "Blackboard Register";
        "message" = "Dynamically provisioned and registered plugin agent node: $AgentName ($RoleDescription)"
    }
    $Shared.neural_bus.coordination_channel += $CoordRecord
    
    $Shared | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemPath -Force -Encoding UTF8
    Write-Output "[SUCCESS] Capabilities matrix updated dynamically inside Blackboard."
}

# 2. Scaffolding custom subagent code block safely under CLM bounds
$NewSubagentPath = Join-Path $SkillsDir "PowerShell\Subagent-$AgentName.ps1"
if (!(Test-Path $NewSubagentPath)) {
    Write-Output "Scaffolding physical subagent script: Subagent-$AgentName.ps1"
    
    $ScriptTemplate = @"
# Synopsis: Dynamic MoA Plugin Subagent - $AgentName
# Description: $RoleDescription
# System Prompt: $TaskSystemPrompt

`$BaseDir = Split-Path (Split-Path `$PSScriptRoot -Parent) -Parent
`$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"
`$LogPath = Join-Path `$BaseDir "Mailbox\subagent_$($AgentName.ToLower())_log.txt"

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

Log-Message "Plugin Subagent-$AgentName Process Initialized."

if (!(Test-Path `$KeyPath)) { exit }
`$ApiKey = (Get-Content `$KeyPath -Raw).Trim()
`$Headers = @{ "Authorization"="Bearer `$ApiKey"; "Content-Type"="application/json" }

while (`$true) {
    Start-Sleep -Seconds 5
    if (!(Test-Path `$SharedMemoryPath)) { continue }

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

        if (`$MyTask) {
            Log-Message "Found Task: `$(`$MyTask.task_id). Executing isolated request..."
            
            `$SystemPrompt = "$TaskSystemPrompt"
            `$TaskPrompt = "Task Description: `$(`$MyTask.description). Execute the task with factual grounding."

            `$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 response back to mailbox pipeline
            `$Mailbox = Get-Content `$MailboxPath -Raw | ConvertFrom-Json
            `$NewMessage = @{
                "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
                "sender" = "Subagent-$AgentName";
                "role" = "$RoleDescription";
                "message" = "[PLUGIN COGNITIVE RESPONSE] - `$AnalysisResult";
                "status" = "TASK_COMPLETED"
            }
            `$Mailbox += `$NewMessage
            `$Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path `$MailboxPath -Force -Encoding UTF8

            # Update Shared Memory
            `$Memory = Get-Content `$SharedMemoryPath -Raw | ConvertFrom-Json
            foreach (`$t in `$Memory.delegated_backlog) {
                if (`$t.task_id -eq `$MyTask.task_id) { `$t.status = "COMPLETE" }
            }
            `$Memory | ConvertTo-Json -Depth 10 | Set-Content -Path `$SharedMemoryPath -Force -Encoding UTF8
            Log-Message "Task `$(`$MyTask.task_id) successfully finalized."
        }
    } catch {
        Log-Message "ERROR: `$(`$_.Exception.Message)"
    }
}
"@
    Set-Content -Path $NewSubagentPath -Value $ScriptTemplate -Force -Encoding UTF8
    Write-Output "[SUCCESS] Dynamic script scaffold completed at $NewSubagentPath"
}

# 3. Provision background thread if active
if ($LaunchAsBackgroundThread) {
    Write-Output "Spawning thread background process for Subagent-$AgentName..."
    $proc = Start-Process powershell -WindowStyle Hidden -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$NewSubagentPath`"" -PassThru
    Write-Output "[ONLINE] Dynamically spawned Subagent-$AgentName (PID: $($proc.Id))"
    
    # Save PID to subagent registry safely without overwriting read-only system structures
    $PidFile = Join-Path $BaseDir "Config\subagent_pids.json"
    if (Test-Path $PidFile) {
        $Pids = Get-Content $PidFile -Raw | ConvertFrom-Json
        $Pids += $proc.Id
        $Pids | ConvertTo-Json | Set-Content -Path $PidFile -Force -Encoding UTF8
    }
}

Write-Output "=== REGISTRATION COMPLETED ==="
