<#
.SYNOPSIS
    ONE-CLICK DEPLOYMENT - JBRhoylle DBA Suite Dashboard v2
.DESCRIPTION
    This script does EVERYTHING to deploy your dashboard:
    1. Runs Get-JBRhoylleDashboardData.ps1 to generate fresh data
    2. Verifies data.json was created successfully (including SQL Intelligence)
    3. Backs up current dashboard
    4. Deploys new dashboard with frontend fixes
    5. Deploys diagnostic page (optional)
    6. Verifies authentication files
    7. Tests the deployment
    8. Opens browser to verify
.NOTES
    Author: Claude AI + Eng. John Bosco Gakumba
    Version: 2.0.0 - Frontend Fix Edition
    Date: January 16, 2026
    
    Changes in v2.0:
    - Updated paths for E:\ProdDB\DBAOps\WebDashboard
    - Added diagnostic.html deployment
    - Added SQL Intelligence data verification
    - Added graceful authentication verification
    - Enhanced error handling and reporting
.EXAMPLE
    # Full deployment with data collection
    .\Deploy-Ultimate-Dashboard.ps1
    
    # Skip data collection (use existing data.json)
    .\Deploy-Ultimate-Dashboard.ps1 -SkipDataCollection
    
    # Preview mode (no changes)
    .\Deploy-Ultimate-Dashboard.ps1 -WhatIf
#>

param(
    [string]$PowerShellScriptPath = "E:\ProdDB\DBAOps\PowerShell\Get-JBRhoylleDashboardData.ps1",
    [string]$WebDashboardPath = "E:\ProdDB\DBAOps\WebDashboard",
    [string]$NewDashboardFile = "index-FIXED.html",
    [string]$DiagnosticFile = "diagnostic.html",
    [switch]$SkipDataCollection,
    [switch]$SkipBrowserTest,
    [switch]$SkipDiagnosticPage,
    [switch]$WhatIf
)

$ErrorActionPreference = "Stop"
$scriptVersion = "2.0.0"

# Helper functions
function Write-Step { param($num, $msg) Write-Host "STEP $num`: $msg" -ForegroundColor Yellow }
function Write-Success { param($msg) Write-Host "  ✅ $msg" -ForegroundColor Green }
function Write-Warning { param($msg) Write-Host "  ⚠️  $msg" -ForegroundColor Yellow }
function Write-Error { param($msg) Write-Host "  ❌ $msg" -ForegroundColor Red }
function Write-Info { param($msg) Write-Host "     $msg" -ForegroundColor Gray }

Write-Host ""
Write-Host "╔════════════════════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║                                                                            ║" -ForegroundColor Cyan
Write-Host "║          🚀 JBRhoylle DBA Suite Dashboard - ONE-CLICK DEPLOYMENT 🚀           ║" -ForegroundColor Cyan
Write-Host "║                                                                            ║" -ForegroundColor Cyan
Write-Host "║                    Version $scriptVersion - Frontend Fix Edition                    ║" -ForegroundColor Cyan
Write-Host "║                                                                            ║" -ForegroundColor Cyan
Write-Host "╚════════════════════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
Write-Host ""

if ($WhatIf) {
    Write-Host "  [WHATIF MODE] No changes will be made - preview only" -ForegroundColor Magenta
    Write-Host ""
}

$startTime = Get-Date

# =============================================
# STEP 0: VERIFY PREREQUISITES
# =============================================
Write-Step 0 "Verifying prerequisites..."

# Check web dashboard path
if (-not (Test-Path $WebDashboardPath)) {
    Write-Error "Web dashboard path not found: $WebDashboardPath"
    Write-Host ""
    Write-Host "  Please specify the correct path:" -ForegroundColor Gray
    Write-Host "  .\Deploy-Ultimate-Dashboard.ps1 -WebDashboardPath 'E:\Your\Path'" -ForegroundColor Gray
    exit 1
}
Write-Success "Web dashboard path found"
Write-Info $WebDashboardPath

# Check for new dashboard file in current directory
$newDashboardPath = Join-Path (Get-Location) $NewDashboardFile
if (-not (Test-Path $newDashboardPath)) {
    # Try alternate names
    $alternateNames = @("index-FIXED.html", "index.html", "ultimate-dashboard-phase1.html")
    $found = $false
    foreach ($name in $alternateNames) {
        $testPath = Join-Path (Get-Location) $name
        if (Test-Path $testPath) {
            $newDashboardPath = $testPath
            $NewDashboardFile = $name
            $found = $true
            break
        }
    }
    if (-not $found) {
        Write-Error "Dashboard file not found in current directory!"
        Write-Info "Expected one of: $($alternateNames -join ', ')"
        Write-Info "Current directory: $(Get-Location)"
        exit 1
    }
}
Write-Success "Dashboard file found: $NewDashboardFile"

# Check for diagnostic file
$diagnosticPath = Join-Path (Get-Location) $DiagnosticFile
$hasDiagnostic = Test-Path $diagnosticPath
if ($hasDiagnostic) {
    Write-Success "Diagnostic file found: $DiagnosticFile"
} else {
    Write-Warning "Diagnostic file not found (optional): $DiagnosticFile"
}

Write-Host ""

# =============================================
# STEP 1: COLLECT FRESH DATA
# =============================================
if (-not $SkipDataCollection) {
    Write-Step 1 "Collecting fresh data from SQL Servers..."
    Write-Info "Script: $PowerShellScriptPath"
    
    if (-not (Test-Path $PowerShellScriptPath)) {
        Write-Error "Data collection script not found!"
        Write-Info "Expected: $PowerShellScriptPath"
        Write-Host ""
        Write-Host "  You can skip this step if data.json already exists:" -ForegroundColor Gray
        Write-Host "  .\Deploy-Ultimate-Dashboard.ps1 -SkipDataCollection" -ForegroundColor Gray
        exit 1
    }
    
    if (-not $WhatIf) {
        try {
            & $PowerShellScriptPath
            Write-Success "Data collection completed!"
        } catch {
            Write-Error "Data collection failed!"
            Write-Info $_.Exception.Message
            exit 1
        }
    } else {
        Write-Info "[WHATIF] Would run: $PowerShellScriptPath"
    }
} else {
    Write-Step 1 "Skipping data collection (using existing data.json)..."
    Write-Info "Use -SkipDataCollection:$false to enable"
}

Write-Host ""

# =============================================
# STEP 2: VERIFY DATA.JSON
# =============================================
Write-Step 2 "Verifying data.json..."

$dataJsonPath = Join-Path $WebDashboardPath "data.json"
Write-Info "Path: $dataJsonPath"

if (-not (Test-Path $dataJsonPath)) {
    Write-Error "data.json not found!"
    Write-Info "Run Get-JBRhoylleDashboardData.ps1 first, or remove -SkipDataCollection"
    exit 1
}

$dataFile = Get-Item $dataJsonPath
$dataAge = (Get-Date) - $dataFile.LastWriteTime
$dataSizeKB = [math]::Round($dataFile.Length / 1KB, 1)

Write-Success "data.json found!"
Write-Info "Size: $dataSizeKB KB"
Write-Info "Modified: $($dataFile.LastWriteTime)"
Write-Info "Age: $([math]::Round($dataAge.TotalMinutes, 1)) minutes"

# Validate JSON and check content
try {
    $jsonContent = Get-Content $dataJsonPath -Raw
    $data = $jsonContent | ConvertFrom-Json
    
    Write-Success "Valid JSON format!"
    Write-Info "Generated at: $($data.generatedAt)"
    
    # Server counts
    $totalServers = $data.servers.all.Count
    $prodServers = $data.servers.prod.Count
    $nonProdServers = $data.servers.nonProd.Count
    
    Write-Info "Total servers: $totalServers"
    Write-Info "Production: $prodServers | Non-Prod: $nonProdServers"
    
    if ($totalServers -eq 0) {
        Write-Warning "No servers found in data.json!"
        Write-Info "Check PowerShell script output for errors"
    } elseif ($totalServers -lt 100) {
        Write-Warning "Only $totalServers servers (expected ~118)"
    } else {
        Write-Success "Server count looks good: $totalServers"
    }
    
    # Compliance frameworks
    $frameworkCount = $data.compliance.scores.Count
    Write-Info "Compliance frameworks: $frameworkCount"
    if ($frameworkCount -eq 0) {
        Write-Warning "No compliance data found!"
    }
    
    # SQL Intelligence (NEW CHECK)
    $sqlIntelCount = $data.sqlIntelligence.Count
    Write-Info "SQL Intelligence groups: $sqlIntelCount"
    if ($sqlIntelCount -eq 0) {
        Write-Warning "No SQL Intelligence data found!"
        Write-Info "SQL version breakdown will not display"
    } else {
        Write-Success "SQL Intelligence data available"
        foreach ($ver in $data.sqlIntelligence | Select-Object -First 3) {
            Write-Info "  - $($ver.version): $($ver.count) servers ($($ver.status))"
        }
    }
    
} catch {
    Write-Error "Invalid JSON format!"
    Write-Info $_.Exception.Message
    exit 1
}

Write-Host ""

# =============================================
# STEP 3: BACKUP CURRENT DASHBOARD
# =============================================
Write-Step 3 "Backing up current dashboard..."

$currentDashboard = Join-Path $WebDashboardPath "index.html"
$backupFolder = Join-Path $WebDashboardPath "backups"
$backupName = "index.html.backup.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
$backupPath = Join-Path $backupFolder $backupName

# Create backup folder if needed
if (-not (Test-Path $backupFolder)) {
    if (-not $WhatIf) {
        New-Item -ItemType Directory -Path $backupFolder -Force | Out-Null
    }
    Write-Info "Created backup folder: backups\"
}

if (Test-Path $currentDashboard) {
    if (-not $WhatIf) {
        Copy-Item $currentDashboard $backupPath -Force
    }
    Write-Success "Backup created: backups\$backupName"
} else {
    Write-Info "No existing dashboard to backup"
}

Write-Host ""

# =============================================
# STEP 4: DEPLOY NEW DASHBOARD
# =============================================
Write-Step 4 "Deploying fixed dashboard..."

$newDashboardSize = [math]::Round((Get-Item $newDashboardPath).Length / 1KB, 1)
Write-Info "Source: $NewDashboardFile ($newDashboardSize KB)"
Write-Info "Target: $currentDashboard"

if (-not $WhatIf) {
    try {
        Copy-Item $newDashboardPath $currentDashboard -Force
        Write-Success "Dashboard deployed successfully!"
    } catch {
        Write-Error "Deployment failed!"
        Write-Info $_.Exception.Message
        exit 1
    }
} else {
    Write-Info "[WHATIF] Would copy $NewDashboardFile to index.html"
}

Write-Host ""

# =============================================
# STEP 5: DEPLOY DIAGNOSTIC PAGE
# =============================================
Write-Step 5 "Deploying diagnostic page..."

if ($SkipDiagnosticPage) {
    Write-Info "Skipped (use -SkipDiagnosticPage:`$false to enable)"
} elseif (-not $hasDiagnostic) {
    Write-Warning "Diagnostic file not found - skipping"
} else {
    $diagnosticTarget = Join-Path $WebDashboardPath "diagnostic.html"
    
    if (-not $WhatIf) {
        try {
            Copy-Item $diagnosticPath $diagnosticTarget -Force
            Write-Success "Diagnostic page deployed!"
            Write-Info "Access at: https://dbaopsdash/diagnostic.html"
        } catch {
            Write-Warning "Could not deploy diagnostic page: $_"
        }
    } else {
        Write-Info "[WHATIF] Would copy diagnostic.html"
    }
}

Write-Host ""

# =============================================
# STEP 6: VERIFY DEPLOYMENT
# =============================================
Write-Step 6 "Verifying deployment..."

if (Test-Path $currentDashboard) {
    $deployedFile = Get-Item $currentDashboard
    $deployedSizeKB = [math]::Round($deployedFile.Length / 1KB, 1)
    
    Write-Success "index.html exists"
    Write-Info "Size: $deployedSizeKB KB"
    Write-Info "Modified: $($deployedFile.LastWriteTime)"
    
    # Content verification
    $content = Get-Content $currentDashboard -Raw
    
    # Check for key indicators
    $checks = @{
        "Dashboard title" = $content -like "*JBRhoylle DBA Suite Dashboard*"
        "SQL Intelligence function" = $content -like "*dashboardData?.sqlIntelligence*"
        "Graceful auth handling" = $content -like "*typeof DBAOpsAuth*"
        "Modal dialog function" = $content -like "*function showModal*"
    }
    
    $allPassed = $true
    foreach ($check in $checks.GetEnumerator()) {
        if ($check.Value) {
            Write-Success $check.Key
        } else {
            Write-Warning "$($check.Key) - NOT FOUND"
            $allPassed = $false
        }
    }
    
    if ($allPassed) {
        Write-Success "All frontend fixes verified!"
    } else {
        Write-Warning "Some fixes may be missing - dashboard should still work"
    }
} else {
    Write-Error "Deployment verification failed - index.html not found!"
    exit 1
}

Write-Host ""

# =============================================
# STEP 7: CHECK AUTHENTICATION FILES
# =============================================
Write-Step 7 "Checking authentication files..."

$apiFolder = Join-Path $WebDashboardPath "api"
$authAspx = Join-Path $apiFolder "auth.aspx"
$authJs = Join-Path $apiFolder "auth.js"

if (Test-Path $apiFolder) {
    Write-Success "api folder exists"
} else {
    Write-Warning "api folder not found!"
}

if (Test-Path $authAspx) {
    $authAspxSize = [math]::Round((Get-Item $authAspx).Length / 1KB, 1)
    Write-Success "auth.aspx found ($authAspxSize KB)"
} else {
    Write-Warning "auth.aspx not found - Windows Auth may not work"
}

if (Test-Path $authJs) {
    $authJsSize = [math]::Round((Get-Item $authJs).Length / 1KB, 1)
    Write-Success "auth.js found ($authJsSize KB)"
} else {
    Write-Warning "auth.js not found - Authentication may fail"
    Write-Info "Dashboard will still work with default viewer permissions"
}

Write-Host ""

# =============================================
# DEPLOYMENT SUMMARY
# =============================================
$duration = (Get-Date) - $startTime

Write-Host "╔════════════════════════════════════════════════════════════════════════════╗" -ForegroundColor Green
Write-Host "║                                                                            ║" -ForegroundColor Green
Write-Host "║                    ✅ DEPLOYMENT SUCCESSFUL! ✅                            ║" -ForegroundColor Green
Write-Host "║                                                                            ║" -ForegroundColor Green
Write-Host "╚════════════════════════════════════════════════════════════════════════════╝" -ForegroundColor Green
Write-Host ""
Write-Host "  Deployment Summary:" -ForegroundColor Cyan
Write-Host "  ─────────────────────────────────────────────" -ForegroundColor Gray
Write-Host "  Total Time:        $([math]::Round($duration.TotalSeconds, 1)) seconds" -ForegroundColor White
Write-Host "  Dashboard:         $currentDashboard" -ForegroundColor White
Write-Host "  Dashboard Size:    $deployedSizeKB KB" -ForegroundColor White
Write-Host "  Data File:         $dataJsonPath" -ForegroundColor White
Write-Host "  Data Size:         $dataSizeKB KB" -ForegroundColor White
Write-Host "  Servers:           $totalServers" -ForegroundColor White
Write-Host "  SQL Versions:      $sqlIntelCount groups" -ForegroundColor White
Write-Host ""

# =============================================
# NEXT STEPS
# =============================================
Write-Host "═══════════════════════════════════════════════════════════════════════════" -ForegroundColor Yellow
Write-Host "  NEXT STEPS:" -ForegroundColor Yellow
Write-Host "═══════════════════════════════════════════════════════════════════════════" -ForegroundColor Yellow
Write-Host ""
Write-Host "  1. Test diagnostic page FIRST (recommended)" -ForegroundColor White
Write-Host "     URL: " -NoNewline; Write-Host "https://dbaopsdash/diagnostic.html" -ForegroundColor Cyan
Write-Host "     - Verify auth.js loads" -ForegroundColor Gray
Write-Host "     - Verify data.json loads" -ForegroundColor Gray
Write-Host "     - Check server count shows $totalServers" -ForegroundColor Gray
Write-Host ""
Write-Host "  2. Open main dashboard" -ForegroundColor White
Write-Host "     URL: " -NoNewline; Write-Host "https://dbaopsdash" -ForegroundColor Cyan
Write-Host ""
Write-Host "  3. Hard refresh to clear cache" -ForegroundColor White
Write-Host "     Press: " -NoNewline; Write-Host "Ctrl + Shift + R" -ForegroundColor Cyan
Write-Host ""
Write-Host "  4. Verify these sections work:" -ForegroundColor White
Write-Host "     - SQL Intelligence shows real version data" -ForegroundColor Gray
Write-Host "     - Server Management lists all $totalServers servers" -ForegroundColor Gray
Write-Host "     - Compliance scorecard shows 4 frameworks" -ForegroundColor Gray
Write-Host ""

# =============================================
# ROLLBACK INSTRUCTIONS
# =============================================
Write-Host "═══════════════════════════════════════════════════════════════════════════" -ForegroundColor DarkGray
Write-Host "  ROLLBACK (if needed):" -ForegroundColor DarkGray
Write-Host "═══════════════════════════════════════════════════════════════════════════" -ForegroundColor DarkGray
Write-Host ""
Write-Host "  Copy-Item '$backupPath' '$currentDashboard' -Force" -ForegroundColor Gray
Write-Host ""

# =============================================
# AUTO-OPEN BROWSER
# =============================================
if (-not $SkipBrowserTest -and -not $WhatIf) {
    Write-Host "  Opening diagnostic page in 3 seconds..." -ForegroundColor Yellow
    Start-Sleep -Seconds 1
    Write-Host "  2..." -ForegroundColor Yellow
    Start-Sleep -Seconds 1
    Write-Host "  1..." -ForegroundColor Yellow
    Start-Sleep -Seconds 1
    
    try {
        # Open diagnostic page first
        if ($hasDiagnostic -and -not $SkipDiagnosticPage) {
            Start-Process "https://dbaopsdash/diagnostic.html"
            Write-Host ""
            Write-Success "Diagnostic page opened!"
        } else {
            Start-Process "https://dbaopsdash"
            Write-Host ""
            Write-Success "Dashboard opened!"
        }
    } catch {
        Write-Host ""
        Write-Warning "Could not auto-open browser"
        Write-Info "Manually open: https://dbaopsdash/diagnostic.html"
    }
}

Write-Host ""
Write-Host "═══════════════════════════════════════════════════════════════════════════" -ForegroundColor Green
Write-Host "  🎉 Deployment Complete! Your dashboard fixes are now live! 🎉" -ForegroundColor Green
Write-Host "═══════════════════════════════════════════════════════════════════════════" -ForegroundColor Green
Write-Host ""
