<#
.SYNOPSIS
    Rotates and cleans up old log files.

.DESCRIPTION
    Removes transcript and log files older than the specified retention period.
    Designed to run as a scheduled task daily.

.PARAMETER RetentionDays
    Number of days to retain log files. Default is 30.

.PARAMETER LogPath
    Path to the logs directory. Default is C:\ClaudeTools\Logs.

.PARAMETER WhatIf
    Shows what would be deleted without actually deleting.

.EXAMPLE
    .\Invoke-LogRotation.ps1
    Removes logs older than 30 days.

.EXAMPLE
    .\Invoke-LogRotation.ps1 -RetentionDays 14 -WhatIf
    Shows what would be deleted with 14-day retention.

.NOTES
    Author: ClaudeTools Automation
    Version: 1.0
#>

[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory=$false)]
    [int]$RetentionDays = 30,

    [Parameter(Mandatory=$false)]
    [string]$LogPath = "C:\ClaudeTools\Logs"
)

$rotationLog = Join-Path $LogPath "rotation.log"
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

function Write-Log {
    param([string]$Message)
    $logEntry = "[$timestamp] $Message"
    Add-Content -Path $rotationLog -Value $logEntry
    Write-Host $logEntry
}

Write-Log "=== Log Rotation Started ==="
Write-Log "Retention Period: $RetentionDays days"
Write-Log "Log Path: $LogPath"

$cutoffDate = (Get-Date).AddDays(-$RetentionDays)
$totalDeleted = 0
$totalSizeFreed = 0

# Find and delete old files
$oldFiles = Get-ChildItem -Path $LogPath -Recurse -File |
    Where-Object { $_.LastWriteTime -lt $cutoffDate -and $_.Name -ne "rotation.log" }

$fileCount = ($oldFiles | Measure-Object).Count
Write-Log "Found $fileCount files older than $RetentionDays days"

foreach ($file in $oldFiles) {
    $fileSize = $file.Length
    $filePath = $file.FullName

    if ($PSCmdlet.ShouldProcess($filePath, "Delete")) {
        try {
            Remove-Item $filePath -Force
            $totalDeleted++
            $totalSizeFreed += $fileSize
            Write-Log "Deleted: $filePath ($([math]::Round($fileSize/1KB, 2)) KB)"
        } catch {
            Write-Log "ERROR deleting $filePath : $_"
        }
    } else {
        Write-Log "WhatIf: Would delete $filePath ($([math]::Round($fileSize/1KB, 2)) KB)"
    }
}

# Delete empty subdirectories
$emptyDirs = Get-ChildItem -Path $LogPath -Directory -Recurse |
    Where-Object { (Get-ChildItem $_.FullName -Force).Count -eq 0 }

foreach ($dir in $emptyDirs) {
    if ($PSCmdlet.ShouldProcess($dir.FullName, "Remove empty directory")) {
        try {
            Remove-Item $dir.FullName -Force
            Write-Log "Removed empty directory: $($dir.FullName)"
        } catch {
            Write-Log "ERROR removing directory $($dir.FullName) : $_"
        }
    }
}

# Summary
$sizeMB = [math]::Round($totalSizeFreed / 1MB, 2)
Write-Log "=== Rotation Complete ==="
Write-Log "Files Deleted: $totalDeleted"
Write-Log "Space Freed: $sizeMB MB"

# Show current disk usage
$currentSize = (Get-ChildItem -Path $LogPath -Recurse -File | Measure-Object -Property Length -Sum).Sum
$currentSizeMB = [math]::Round($currentSize / 1MB, 2)
Write-Log "Current Log Directory Size: $currentSizeMB MB"
