# Synopsis: Generates workspace dashboard views.
# Description: Aggregates active status logs and compiles dynamic HTML reporting interfaces.

$BaseDir = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$ProjectsDir = Join-Path $BaseDir "Projects"
$DeliverablesDir = Join-Path $BaseDir "Deliverables"
$HubPath = Join-Path $DeliverablesDir "Workspace_Consolidation_Hub.html"
$DashboardPath = Join-Path $DeliverablesDir "AgentOS_Dashboard.html"
$CsvPath = Join-Path $DeliverablesDir "Project_Task_Tracker.csv"
$StatePath = Join-Path $BaseDir "Config\active_state.json"

# Clear temporary mailbox pipes safely
$MailboxPath = Join-Path $BaseDir "Mailbox"
if (Test-Path $MailboxPath) {
    Get-ChildItem -Path $MailboxPath -Filter "A2A_*.json" | Remove-Item -Force -ErrorAction SilentlyContinue
}

# 1. Parse Project Task Tracker CSV
$Tasks = @()
if (Test-Path $CsvPath) {
    $Tasks = Import-Csv -Path $CsvPath
}

$TotalTasks = $Tasks.Count
$CompletedTasks = ($Tasks | Where-Object { $_.Status -eq "Complete" -or $_.Status -eq "Completed" }).Count
$PendingTasks = $TotalTasks - $CompletedTasks

# 2. Parse active state metadata
$CurrentProject = "Unknown"
$CurrentGoal = "Unknown"
if (Test-Path $StatePath) {
    try {
        $StateJson = Get-Content $StatePath -Raw | ConvertFrom-Json
        $CurrentProject = $StateJson.current_project
        $CurrentGoal = $StateJson.current_goal
    } catch {
        # Fallback for dynamic reading
    }
}

# 3. Compile dynamically visualized Project Task Tracker Table for Workspace Hub
$TaskTableRows = ""
foreach ($Task in $Tasks) {
    $StatusBadgeClass = "badge-progress"
    if ($Task.Status -eq "Complete" -or $Task.Status -eq "Completed") {
        $StatusBadgeClass = "badge-completed"
    } elseif ($Task.Status -eq "Pending") {
        $StatusBadgeClass = "badge-added"
    }
    
    $TaskTableRows += "<tr>
        <td><strong>$($Task.Task)</strong></td>
        <td>$($Task.Resource)</td>
        <td>$($Task.Priority)</td>
        <td><span class='badge $StatusBadgeClass'>$($Task.Status)</span></td>
        <td>$($Task.Timeline)</td>
        <td>$($Task.Notes)</td>
    </tr>"
}

$CurrentUTC = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")

# Generate the Workspace Consolidation Hub HTML with embedded dynamic dashboarding
$HubHtml = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AgentOS - Workspace Consolidation Hub</title>
    <style>
        :root {
            --bg-color: #0b0f19;
            --card-bg: #111827;
            --border-color: #1f2937;
            --text-primary: #f9fafb;
            --text-secondary: #9ca3af;
            --accent-green: #10b981;
            --accent-blue: #3b82f6;
            --accent-purple: #8b5cf6;
            --accent-orange: #f59e0b;
        }
        body {
            font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-primary);
            margin: 0;
            padding: 24px;
            line-height: 1.5;
        }
        .header {
            border-bottom: 2px solid var(--border-color);
            padding-bottom: 16px;
            margin-bottom: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(to right, #3b82f6, #10b981);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .grid-3 {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 24px;
        }
        .stat-card {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 20px;
            text-align: center;
        }
        .stat-val {
            font-size: 32px;
            font-weight: 700;
            margin: 8px 0;
        }
        .stat-card.blue .stat-val { color: var(--accent-blue); }
        .stat-card.orange .stat-val { color: var(--accent-orange); }
        .stat-card.green .stat-val { color: var(--accent-green); }
        .card {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
        }
        .card-header {
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 12px;
            margin-bottom: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .card-header h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        th, td {
            text-align: left;
            padding: 12px;
            border-bottom: 1px solid var(--border-color);
        }
        th {
            color: var(--text-secondary);
            font-weight: 600;
        }
        .badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }
        .badge-progress { background-color: rgba(245, 158, 11, 0.15); color: var(--accent-orange); }
        .badge-completed { background-color: rgba(16, 185, 129, 0.15); color: var(--accent-green); }
        .badge-added { background-color: rgba(59, 130, 246, 0.15); color: var(--accent-blue); }
    </style>
</head>
<body>
    <div class="header">
        <div>
            <h1>Workspace Consolidation Hub</h1>
            <div style="color: var(--text-secondary); font-size: 14px; margin-top: 4px;">Tactical Project Portfolio & Sanitation Monitor</div>
        </div>
        <div style="font-family: monospace; color: var(--accent-green);">LAST_CONSOLIDATION_METRIC: $CurrentUTC</div>
    </div>

    <!-- STATS -->
    <div class="grid-3">
        <div class="stat-card blue">
            <div style="color: var(--text-secondary); font-size: 14px;">Total Project Tasks</div>
            <div class="stat-val">$TotalTasks</div>
            <div style="font-size: 11px; color: var(--text-secondary);">Direct CSV Aggregation</div>
        </div>
        <div class="stat-card orange">
            <div style="color: var(--text-secondary); font-size: 14px;">Pending Tasks</div>
            <div class="stat-val">$PendingTasks</div>
            <div style="font-size: 11px; color: var(--text-secondary);">Active workflow targets</div>
        </div>
        <div class="stat-card green">
            <div style="color: var(--text-secondary); font-size: 14px;">Completed Tasks</div>
            <div class="stat-val" style="color: var(--accent-green);">$CompletedTasks</div>
            <div style="font-size: 11px; color: var(--text-secondary);">Quality assured and closed</div>
        </div>
    </div>

    <!-- ACTIVE STATE SYNC TELEMETRY CARD -->
    <div class="card" style="border-left: 4px solid var(--accent-blue);">
        <div class="card-header">
            <h2>Current Orchestration State Context</h2>
            <span class="badge badge-added">Active Session Sync</span>
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; font-size: 14px;">
            <div><strong>Active Project:</strong> <span style="color: var(--accent-blue); font-weight: 600;">$CurrentProject</span></div>
            <div><strong>Active Goal:</strong> <span style="color: var(--accent-green); font-weight: 600;">$CurrentGoal</span></div>
        </div>
    </div>

    <!-- PORTFOLIO TASK TRACKER TABLE -->
    <div class="card">
        <div class="card-header">
            <h2>Active Task Tracker (Dynamically Compiled from CSV)</h2>
            <span class="badge badge-completed">Auto-Compiled</span>
        </div>
        <table>
            <thead>
                <tr>
                    <th>Task Name</th>
                    <th>Resource</th>
                    <th>Priority</th>
                    <th>Status</th>
                    <th>Timeline</th>
                    <th>Notes/Details</th>
                </tr>
            </thead>
            <tbody>
                $TaskTableRows
            </tbody>
        </table>
    </div>
</body>
</html>
"@

Set-Content -Path $HubPath -Value $HubHtml -Force -Encoding UTF8

Write-Output "[SYSTEM] Multi-Agent workspace consolidated and synchronized at $CurrentUTC"
Write-Output "[SYSTEM] Hub visualization successfully generated at: $HubPath"
