# Synopsis: Front-end UI visual sensory node representation.
# Description: Conducts exactly ONE coordination pass: analyzes the message stream, appends its reply, and updates active statuses.

$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"

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

if (!(Test-Path $MailboxPath)) { exit }

try {
    $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
    if ($Mailbox.Count -eq 0) { exit }
    
    $LastMessage = $Mailbox[-1]
    
    # AgentOSH replies if the last message was from the Supervisor or other subagents and does not already represent a AgentOSH reply
    if ($LastMessage.sender -ne "AgentOSH (Front-End)" -and $LastMessage.status -ne "SYS_INIT") {
        Write-Output "[MIRROR OSH COGNITIVE] Analyzing latest message stream... Generating reply..."
        
        # Construct conversational context for isolated prompt
        $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 response back to the stream
        $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
        $NewMessage = @{
            "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
            "sender" = "AgentOSH (Front-End)"
            "role" = "Front-End UI"
            "message" = $ReplyText
            "status" = "UI_RESPONSE"
        }
        $Mailbox += $NewMessage
        $Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path $MailboxPath -Force -Encoding UTF8
        
        # Update Active State
        if (Test-Path $StatePath) {
            $State = Get-Content $StatePath -Raw | ConvertFrom-Json
            foreach ($agent in $State.agents) {
                if ($agent.name -eq "AgentOSH") {
                    $agent.status = "ONLINE"
                    $agent.last_active = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
                }
            }
            $State | ConvertTo-Json -Depth 10 | Set-Content -Path $StatePath -Force -Encoding UTF8
        }
    } else {
        Write-Output "Latest message is from AgentOSH or is Init. Skipping front-end execution pass."
    }
} catch {
    Write-Output "[ERROR] AgentOSH failed cognitive thread step: $($_.Exception.Message)"
}
