# Synopsis: Grounded cognitive data compiler node.
# Description: Conducts exactly ONE workspace sweep: scans directories, updates files, and writes analysis.

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_processor_log.txt"
$SkillsDir = Join-Path $BaseDir "Skills"

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

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

if (!(Test-Path $SharedMemoryPath)) {
    Log-Message "Shared memory file not found. BaseDir evaluated as: $BaseDir. Standing down."
    exit
}

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

    if ($MyTask) {
        Log-Message "Found Assigned Task: $($MyTask.task_id). Description: $($MyTask.description)"

        # LOCAL GROUNDING: Search for files referenced in task description
        $GroundedContext = "--- LOCAL GROUNDED FILE CONTEXT ---`n"
        $DeliverablesDir = Join-Path $BaseDir "Deliverables"
        
        if (Test-Path $DeliverablesDir) {
            $Files = Get-ChildItem -Path $DeliverablesDir -File
            foreach ($file in $Files) {
                if ($file.Name -match "tracker" -or $file.Name -match "status" -or $MyTask.description -match $file.BaseName) {
                    Log-Message "Grounding context with file: $($file.Name)"
                    $Content = Get-Content $file.FullName -Raw
                    $GroundedContext += "[FILE: Deliverables\$($file.Name)]`n$Content`n`n"
                }
            }
        }
        $GroundedContext += "--- END LOCAL CONTEXT ---"

        # Formulate prompt
        $SystemPrompt = "You are the Data Processor subagent (Subagent-DataProcessor) inside AgentOS. You are an expert data analyst and CSV pipeline manager. If this task requires executing local actions, creating files, or modifying trackers, you must write a CLM-compliant PowerShell script wrapped inside [PS_CODE]...[/PS_CODE] tags. The script must NOT use static .NET method calls or COM objects, and must resolve paths relative to the environment root."
        $TaskPrompt = "Execute the following task: $($MyTask.description)`n`n$GroundedContext`n`nProvide your analysis and output any script execution block inside [PS_CODE] tags if needed."

        Log-Message "Formulating API payload with model: $Model"
        $Body = @{
            "model" = $Model
            "messages" = @(
                @{ "role" = "system"; "content" = $SystemPrompt },
                @{ "role" = "user"; "content" = $TaskPrompt }
            )
        } | ConvertTo-Json -Depth 10

        Log-Message "Sending API request..."
        $Response = Invoke-RestMethod -Uri $Endpoint -Method Post -Headers $Headers -Body $Body
        $AnalysisResult = $Response.choices[0].message.content
        Log-Message "API call success."

        # Check if dynamic script execution is required
        if ($AnalysisResult -match '(?s)\[PS_CODE\](.*?)\[/PS_CODE\]') {
            $Code = $Matches[1].Trim()
            $TempScript = Join-Path $SkillsDir "temp_$($MyTask.task_id).ps1"
            
            Log-Message "AUTONOMOUS PATH: Saving dynamically generated script to: temp_$($MyTask.task_id).ps1"
            Set-Content -Path $TempScript -Value $Code -Force -Encoding UTF8
            
            Log-Message "Executing dynamic script block..."
            $ExecOut = & $TempScript 2>&1 | Out-String
            Log-Message "Execution output captured."
            
            # Clean up temp script safely
            if (Test-Path $TempScript) { Remove-Item $TempScript -Force }
            
            $AnalysisResult = $AnalysisResult -replace '(?s)\[PS_CODE\].*?\[/PS_CODE\]', ""
            $AnalysisResult += "`n`n### Autonomous Script Execution Log`n"
        }

        # Write subagent response to Mailbox
        $Mailbox = Get-Content $MailboxPath -Raw | ConvertFrom-Json
        $NewMessage = @{
            "timestamp" = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
            "sender" = "Subagent-DataProcessor"
            "role" = "Data Compiler"
            "message" = $AnalysisResult
            "status" = "TASK_COMPLETED"
        }
        $Mailbox += $NewMessage
        $Mailbox | ConvertTo-Json -Depth 10 | Set-Content -Path $MailboxPath -Force -Encoding UTF8

        # Update shared memory
        $MyTask.status = "COMPLETE"
        $Memory | ConvertTo-Json -Depth 10 | Set-Content -Path $SharedMemoryPath -Force -Encoding UTF8
        Log-Message "Task $($MyTask.task_id) completed successfully."
    } else {
        Log-Message "No assigned tasks found for DataProcessor. Standing down."
    }
} catch {
    Log-Message "ERROR inside DataProcessor sweep: $($_.Exception.Message)"
}
