#Requires -Version 5.1
#Requires -RunAsAdministrator

<#
.SYNOPSIS
    Sets up automated weekly performance monitoring via Windows Task Scheduler

.DESCRIPTION
    Creates a scheduled task to run Weekly-Performance-Monitor.ps1 every Monday at 6 AM.
    Can optionally enable conditional VACUUM ANALYZE based on dead tuple thresholds.

.PARAMETER Uninstall
    Remove the scheduled task

.PARAMETER TaskTime
    Time to run the task (default: 6am)

.PARAMETER DayOfWeek
    Day of week to run (default: Monday)

.PARAMETER EnableAutoVacuumAnalyze
    Enable conditional VACUUM ANALYZE for tables above dead tuple thresholds

.PARAMETER DeadTupleThreshold
    Minimum dead tuples before VACUUM ANALYZE runs (default: 10000)

.PARAMETER DeadTuplePercentThreshold
    Minimum dead tuple percentage before VACUUM ANALYZE runs (default: 20)

.EXAMPLE
    .\Setup-Weekly-Monitor.ps1
    
.EXAMPLE
    .\Setup-Weekly-Monitor.ps1 -TaskTime "3am" -DayOfWeek Sunday

.EXAMPLE
    .\Setup-Weekly-Monitor.ps1 -EnableAutoVacuumAnalyze -DeadTupleThreshold 10000 -DeadTuplePercentThreshold 20

.EXAMPLE
    .\Setup-Weekly-Monitor.ps1 -Uninstall
#>

[CmdletBinding()]
param (
    [Parameter()]
    [switch]$Uninstall,

    [Parameter()]
    [string]$TaskTime = "6am",

    [Parameter()]
    [ValidateSet('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')]
    [string]$DayOfWeek = 'Monday',

    [Parameter()]
    [switch]$EnableAutoVacuumAnalyze,

    [Parameter()]
    [ValidateRange(1, [int]::MaxValue)]
    [int]$DeadTupleThreshold = 10000,

    [Parameter()]
    [ValidateRange(0.01, 100.0)]
    [double]$DeadTuplePercentThreshold = 20.0
)

$ErrorActionPreference = "Stop"

$TaskName = "Jellyfin Database Weekly Monitor"
$ScriptRoot = Split-Path -Parent $PSCommandPath
$MonitorScript = Join-Path $ScriptRoot "Weekly-Performance-Monitor.ps1"

# ============================================================================
# Functions
# ============================================================================

function Write-ColorOutput {
    param(
        [string]$Message,
        [ConsoleColor]$Color = 'White'
    )
    Write-Host $Message -ForegroundColor $Color
}

function Test-IsAdmin {
    $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
    return $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# ============================================================================
# Main
# ============================================================================

Write-ColorOutput "`n========================================" -Color Cyan
Write-ColorOutput "Jellyfin DB Monitor Setup" -Color Cyan
Write-ColorOutput "========================================`n" -Color Cyan

# Check if running as administrator
if (-not (Test-IsAdmin)) {
    Write-ColorOutput "❌ This script must be run as Administrator" -Color Red
    Write-ColorOutput "   Right-click PowerShell and select 'Run as Administrator'" -Color Yellow
    exit 1
}

# Uninstall if requested
if ($Uninstall) {
    Write-ColorOutput "Removing scheduled task..." -Color Yellow
    
    $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
    
    if ($task) {
        Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
        Write-ColorOutput "✅ Scheduled task removed successfully" -Color Green
    } else {
        Write-ColorOutput "⚠️ Scheduled task not found" -Color Yellow
    }
    
    exit 0
}

# Check if monitor script exists
if (-not (Test-Path $MonitorScript)) {
    Write-ColorOutput "❌ Monitor script not found: $MonitorScript" -Color Red
    exit 1
}

Write-ColorOutput "Configuration:" -Color Cyan
Write-ColorOutput "  Task Name: $TaskName" -Color White
Write-ColorOutput "  Script: $MonitorScript" -Color White
Write-ColorOutput "  Schedule: Every $DayOfWeek at $TaskTime" -Color White
if ($EnableAutoVacuumAnalyze) {
    Write-ColorOutput "  Auto VACUUM ANALYZE: Enabled (dead tuples >= $DeadTupleThreshold, dead percent >= $DeadTuplePercentThreshold)" -Color White
} else {
    Write-ColorOutput "  Auto VACUUM ANALYZE: Disabled" -Color White
}
Write-ColorOutput ""

# Remove existing task if present
$existingTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
if ($existingTask) {
    Write-ColorOutput "⚠️ Existing task found. Removing..." -Color Yellow
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}

# Create scheduled task action
Write-ColorOutput "Creating scheduled task..." -Color Cyan

$scriptArguments = "-NoProfile -ExecutionPolicy Bypass -File `"$MonitorScript`""
if ($EnableAutoVacuumAnalyze) {
    $scriptArguments += " -AutoVacuumAnalyze -DeadTupleThreshold $DeadTupleThreshold -DeadTuplePercentThreshold $DeadTuplePercentThreshold"
}

$action = New-ScheduledTaskAction `
    -Execute "PowerShell.exe" `
    -Argument $scriptArguments

# Create trigger
$trigger = New-ScheduledTaskTrigger `
    -Weekly `
    -DaysOfWeek $DayOfWeek `
    -At $TaskTime

# Task settings
$settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -StartWhenAvailable `
    -RunOnlyIfNetworkAvailable `
    -ExecutionTimeLimit (New-TimeSpan -Hours 2)

# Task principal (run as current user)
$principal = New-ScheduledTaskPrincipal `
    -UserId $env:USERNAME `
    -LogonType S4U `
    -RunLevel Highest

# Register the task
try {
    Register-ScheduledTask `
        -TaskName $TaskName `
        -Action $action `
        -Trigger $trigger `
        -Settings $settings `
        -Principal $principal `
        -Description "Automated weekly performance monitoring for Jellyfin PostgreSQL database" | Out-Null
    
    Write-ColorOutput "✅ Scheduled task created successfully!" -Color Green
    Write-ColorOutput ""
    
    # Verify task
    $task = Get-ScheduledTask -TaskName $TaskName
    $nextRun = $task.Triggers[0].StartBoundary
    
    Write-ColorOutput "Task Details:" -Color Cyan
    Write-ColorOutput "  Status: $($task.State)" -Color White
    Write-ColorOutput "  Next Run: $nextRun" -Color White
    Write-ColorOutput ""
    
    # Test run option
    Write-ColorOutput "Would you like to test the task now? (y/n): " -Color Yellow -NoNewline
    $response = Read-Host
    
    if ($response -eq 'y' -or $response -eq 'Y') {
        Write-ColorOutput "`nRunning test..." -Color Cyan
        Start-ScheduledTask -TaskName $TaskName
        Start-Sleep -Seconds 2
        
        $taskInfo = Get-ScheduledTask -TaskName $TaskName | Get-ScheduledTaskInfo
        Write-ColorOutput "Last Run Time: $($taskInfo.LastRunTime)" -Color White
        Write-ColorOutput "Last Result: $($taskInfo.LastTaskResult)" -Color White
        
        if ($taskInfo.LastTaskResult -eq 0) {
            Write-ColorOutput "✅ Test run completed successfully!" -Color Green
        } else {
            Write-ColorOutput "⚠️ Test run completed with code: $($taskInfo.LastTaskResult)" -Color Yellow
        }
    }
    
} catch {
    Write-ColorOutput "❌ Failed to create scheduled task: $_" -Color Red
    exit 1
}

Write-ColorOutput "`n========================================" -Color Green
Write-ColorOutput "Setup Complete!" -Color Green
Write-ColorOutput "========================================" -Color Green
Write-ColorOutput ""
Write-ColorOutput "Monitoring is now automated!" -Color Cyan
Write-ColorOutput ""
Write-ColorOutput "To manage the task:" -Color White
Write-ColorOutput "  View: Get-ScheduledTask -TaskName '$TaskName'" -Color Gray
Write-ColorOutput "  Run now: Start-ScheduledTask -TaskName '$TaskName'" -Color Gray
Write-ColorOutput "  Disable: Disable-ScheduledTask -TaskName '$TaskName'" -Color Gray
Write-ColorOutput "  Remove: .\Setup-Weekly-Monitor.ps1 -Uninstall" -Color Gray
Write-ColorOutput ""
Write-ColorOutput "Reports will be saved to: reports\weekly" -Color Yellow
Write-ColorOutput "========================================`n" -Color Green
