param(
    [Parameter(Mandatory=$true)]
    [string]$Prompt,
    
    [ValidateSet("Worker", "QA", "Utility")]
    [string]$Role = "Utility",

    [string]$Model = "flash-lite",

    [switch]$ShowContext
)

# Ensure the session has the API key loaded
if (Test-Path "C:\projects\misc\setup_gemini.ps1") {
    . C:\projects\misc\setup_gemini.ps1
}

$SystemPrompts = @{
    "Worker" = "STRICT SYSTEM DIRECTIVE: You are a stateless Tier 3 Worker (Contributor). Your goal is to generate high-quality code or diffs based on the provided ticket. DO NOT USE ANY TOOLS (no write_file, no run_shell_command, etc.). ONLY output the clean code or the requested diff inside XML-style tags if requested, otherwise just the code. No pleasantries."
    "QA"     = "STRICT SYSTEM DIRECTIVE: You are a stateless Tier 4 QA Agent. Your goal is to analyze the provided error trace and compress it into a surgical, 20-word fix. DO NOT USE ANY TOOLS. ONLY output the compressed fix. No explanations."
    "Utility" = "STRICT SYSTEM DIRECTIVE: You are a stateless utility function. DO NOT USE ANY TOOLS. ONLY output the exact requested text, code, or JSON."
}

$SelectedPrompt = $SystemPrompts[$Role]
$SafePrompt = "$SelectedPrompt`n`nUSER PROMPT:`n$Prompt"

# Ensure log directory exists
if (-not (Test-Path "logs")) { New-Item -ItemType Directory -Path "logs" | Out-Null }
$LogFile = "logs/mma_delegation.log"
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

$LogEntry = @"
--------------------------------------------------
TIMESTAMP: $Timestamp
TIER: $Role
SYSTEM PROMPT: $SelectedPrompt
USER PROMPT: $Prompt
--------------------------------------------------
"@
$LogEntry | Out-File -FilePath $LogFile -Append -Encoding utf8

if ($ShowContext) {
    Write-Host "`n[MMA ORCHESTRATOR] Spawning Tier: $Role" -ForegroundColor Cyan
    Write-Host "[MMA SYSTEM PROMPT]:`n$SelectedPrompt" -ForegroundColor Gray
    Write-Host "[USER PROMPT]:`n$Prompt" -ForegroundColor White
    Write-Host "--------------------------------------------------"
}

# Execute headless Gemini using -p, suppressing stderr noise
$jsonOutput = gemini -p $SafePrompt --model $Model --output-format json 2>$null

try {
    # Extract only the JSON part
    $fullString = $jsonOutput -join "`n"
    $jsonStartIndex = $fullString.IndexOf("{")
    
    if ($jsonStartIndex -ge 0) {
        $cleanJsonString = $fullString.Substring($jsonStartIndex)
        $parsed = $cleanJsonString | ConvertFrom-Json
        
        # Log response
        "RESPONSE:`n$($parsed.response)" | Out-File -FilePath $LogFile -Append -Encoding utf8
        
        # Output only the clean response text
        Write-Output $parsed.response
    } else {
        "ERROR: No JSON found in output.`n$fullString" | Out-File -FilePath $LogFile -Append
        Write-Warning "No JSON object found in output."
        Write-Output $fullString
    }
} catch {
    "FATAL ERROR: Parsing failed.`n$_" | Out-File -FilePath $LogFile -Append
    # Fallback if parsing fails
    Write-Warning "Failed to parse JSON from sub-agent. Raw output:"
    Write-Output $jsonOutput
}
