# Synopsis: Launches the visual Mix of Agents dashboard and schedules cognitive sweeps.
# Description: Starts the local interface, cleans up PIDs, and executes a baseline single sweep.

$BaseDir = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$EdgeCandidates = @()
$EdgeCommand = Get-Command "msedge.exe" -ErrorAction SilentlyContinue
if ($EdgeCommand) { $EdgeCandidates += $EdgeCommand.Source }
if ($env:ProgramFiles) { $EdgeCandidates += (Join-Path $env:ProgramFiles "Microsoft\Edge\Application\msedge.exe") }
if (${env:ProgramFiles(x86)}) { $EdgeCandidates += (Join-Path ${env:ProgramFiles(x86)} "Microsoft\Edge\Application\msedge.exe") }
$EdgePath = $EdgeCandidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1
$WorkspacePath = Join-Path $BaseDir "Deliverables\Mix_of_Agents_Workspace.html"
$PidFile = Join-Path $BaseDir "Config\subagent_pids.json"
$ConfigFile = Join-Path $BaseDir "Config\agent_config.json"
$Timestamp = (Get-Date).ToString("yyyyMMddHHmmss")
$UserDataDir = Join-Path $env:TEMP "EdgeMoAWorkspace_$Timestamp"

Write-Output "[SYSTEM] Commencing launch of Cognitive Agent network..."

# 1. Purge old background processes to ensure absolute resource hygiene
if (Test-Path $PidFile) {
    try {
        $OldPids = Get-Content $PidFile -Raw | ConvertFrom-Json
        foreach ($pidVal in $OldPids) {
            if ($pidVal -and $pidVal -ne $PID) {
                Write-Output "[SYSTEM] Terminating old subagent process ID: $pidVal"
                Stop-Process -Id $pidVal -Force -ErrorAction SilentlyContinue | Out-Null
            }
        }
    } catch {
        Write-Output "[WARNING] Failed to clean up old PIDs gracefully."
    }
}

# Clean old background job sweeps to prevent thread leaks
Get-Job | Remove-Job -Force -ErrorAction SilentlyContinue

# 2. Launch Workspace Visual Interface
if (Test-Path $EdgePath) {
    if (Test-Path $WorkspacePath) {
        $FullPath = (Get-Item $WorkspacePath).FullName.Replace("\", "/")
        $UriPath = "file:///$FullPath"
        Start-Process -FilePath $EdgePath -ArgumentList `
            "--disable-web-security", `
            "--allow-file-access-from-files", `
            "--user-data-dir=`"$UserDataDir`"", `
            "--no-first-run", `
            "--no-default-browser-check", `
            "--new-window", `
            "`"$UriPath`""
        Write-Output "[SUCCESS] Multi-Agent visual workspace deployed."
    }
} else {
    Write-Output "[WARNING] Edge browser not found. Please open workspace file manually: $WorkspacePath"
}

# 3. Trigger Initial Single Coordination Sweep (non-polling)
$Scheduler = Join-Path $PSScriptRoot "Schedule-MoASweep.ps1"
if (Test-Path $Scheduler) {
    Write-Output "[SYSTEM] Invoking initial single-execution sweep of all subagents..."
    & $Scheduler -TargetAgent "All"
}
