param(
    [string]$BaseDir,
    [bool]$OfflineMode = $false
)

# Synopsis: Master bootstrap installer and launcher for Project Mix of Agents (MoA).
# Description: This script serves as the single drop-in entry point for any DoW Project Manager.
# It handles VDI environment checking, directory scaffolding, offline library validation, 
# API credential verification, and thread job orchestration seamlessly under CLM rules.

if (-not $BaseDir) { $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 { }
}
$ConfigDir = Join-Path $BaseDir "Config"
$MailboxDir = Join-Path $BaseDir "Mailbox"
$SkillsDir = Join-Path $BaseDir "Skills"
$DeliverablesDir = Join-Path $BaseDir "Deliverables"
$LibDir = Join-Path $BaseDir "lib"
$KeyPath = Join-Path $ConfigDir "GenAI_Key.txt"

Write-Output "=================================================================="
Write-Output "  MIX OF AGENTS (MoA) - AUTONOMOUS ECOSYSTEM DEPLOYER & BOOTSTRAP"
Write-Output "=================================================================="
Write-Output "Target Workspace: $BaseDir"

# 1. Environment Scaffolding
Write-Output "`n[1/5] Scaffolding physical directory matrices..."
$Folders = @($ConfigDir, $MailboxDir, $SkillsDir, $DeliverablesDir, $LibDir)
foreach ($f in $Folders) {
    if (!(Test-Path $f)) {
        New-Item -ItemType Directory -Path $f -Force | Out-Null
        Write-Output "Created directory: $f"
    } else {
        Write-Output "Verified directory: $f"
    }
}

# 2. Key Validation Check
Write-Output "`n[2/5] Validating API Credential Integrity..."
if (!(Test-Path $KeyPath)) {
    Write-Output "WARNING: API Key not found at '$KeyPath'."
    Write-Output "To initialize the cognitive threads, please drop your secure Bearer Token in: $KeyPath"
    # Create empty template file
    Set-Content -Path $KeyPath -Value "DROP_YOUR_API_KEY_HERE" -Force -Encoding UTF8
} else {
    $KeyVal = (Get-Content $KeyPath -Raw).Trim()
    if ($KeyVal -eq "DROP_YOUR_API_KEY_HERE" -or $KeyVal.Length -lt 10) {
        Write-Output "CRITICAL: Pinned API token is missing or is the default placeholder. Cognitive nodes will standby in OFFLINE mode."
    } else {
        Write-Output "SUCCESS: Bearer token format validated."
    }
}

# 3. Offline Frontend Dependency Validation
Write-Output "`n[3/5] Auditing offline UI dependencies..."
$Libs = @("jspdf.umd.min.js", "marked.min.js", "pdf.min.js", "pdf.worker.min.js")
$LibMissing = $false
foreach ($l in $Libs) {
    $LPath = Join-Path $LibDir $l
    if (!(Test-Path $LPath)) {
        Write-Output "WARNING: Missing offline rendering asset: $l"
        $LibMissing = $true
    } else {
        Write-Output "Verified offline asset: $l"
    }
}
if ($LibMissing) {
    Write-Output "Note: Visual UI rendering may attempt proxy fallbacks if air-gap dependencies are incomplete."
}

# 4. Spawning Autonomous Thread Mesh
Write-Output "`n[4/5] Provisioning asynchronous VDI thread mesh..."
$Launcher = Join-Path $SkillsDir "Launch-MoA.ps1"
if (Test-Path $Launcher) {
    Write-Output "Executing node orchestration launcher..."
    & $Launcher
} else {
    Write-Output "ERROR: Core launcher '$Launcher' not found in workspace."
}

# 5. Performing Verification Baseline Step
Write-Output "`n[5/5] Executing initial supervisor verification cycle..."
$StepSkill = Join-Path $SkillsDir "Step-MoA.ps1"
if (Test-Path $StepSkill) {
    & $StepSkill
} else {
    Write-Output "ERROR: Supervisor step '$StepSkill' not found in workspace."
}

Write-Output "`n=================================================================="
Write-Output "  MoA FRAMEWORK SECURELY DEPLOYED AND RUNNING"
Write-Output "  Open 'Deliverables\Mix_of_Agents_Workspace.html' to monitor."
Write-Output "=================================================================="

