#!/usr/bin/env pwsh
<#
.SYNOPSIS
    Fixes StyleCop warnings in C# files.

.DESCRIPTION
    Automatically fixes common StyleCop warnings:
    - SA1413: Adds trailing commas to multi-line initializers
    - SA1515: Adds blank lines before single-line comments
    - SA1518: Ensures files end with single newline
    
.PARAMETER Path
    The root path to search for C# files. Defaults to "MediaBrowser.Model"

.PARAMETER DryRun
    If specified, shows what would be changed without actually modifying files

.EXAMPLE
    .\FixStyleCopWarnings.ps1 -DryRun
#>

param(
    [string]$Path = "MediaBrowser.Model",
    [switch]$DryRun
)

$ErrorActionPreference = "Stop"

function Fix-TrailingCommas {
    param([string]$Content)
    
    $modified = $false
    $lines = $content -split '\r?\n'
    
    for ($i = 0; $i -lt $lines.Length - 1; $i++) {
        $currentLine = $lines[$i]
        $nextLine = $lines[$i + 1]
        
        # Check if current line ends with a property/value without comma
        # and next line closes the initializer
        if ($currentLine -match '^\s+\w+\s*=\s*.+[^,]\s*$' -and $nextLine -match '^\s*[}\)]') {
            $lines[$i] = $currentLine.TrimEnd() + ','
            $modified = $true
        }
    }
    
    if ($modified) {
        return ($lines -join "`n")
    }
    
    return $Content
}

function Fix-BlankLinesBeforeComments {
    param([string]$Content)
    
    $modified = $false
    $lines = $content -split '\r?\n'
    $newLines = @()
    
    for ($i = 0; $i -lt $lines.Length; $i++) {
        $currentLine = $lines[$i]
        
        # Check if this is a single-line comment
        if ($currentLine -match '^\s+//\s+\w') {
            # Check if previous line exists and is not blank
            if ($i -gt 0) {
                $prevLine = $lines[$i - 1]
                $prevLineIsBlank = [string]::IsNullOrWhiteSpace($prevLine)
                $prevLineIsOpenBrace = $prevLine -match '\{\s*$'
                $prevLineIsComment = $prevLine -match '^\s*//'
                
                # Add blank line if previous line is not blank, not open brace, not another comment
                if (-not $prevLineIsBlank -and -not $prevLineIsOpenBrace -and -not $prevLineIsComment) {
                    $newLines += ""
                    $modified = $true
                }
            }
        }
        
        $newLines += $currentLine
    }
    
    if ($modified) {
        return ($newLines -join "`n")
    }
    
    return $Content
}

function Fix-FileEnding {
    param([string]$Content)
    
    # Ensure file ends with exactly one newline
    $trimmed = $Content.TrimEnd("`r", "`n", " ", "`t")
    return $trimmed + "`n"
}

function Fix-StyleCopWarnings {
    param(
        [string]$FilePath,
        [switch]$DryRun
    )
    
    $content = Get-Content -Path $FilePath -Raw
    $originalContent = $content
    
    # Apply fixes
    $content = Fix-TrailingCommas -Content $content
    $content = Fix-BlankLinesBeforeComments -Content $content
    $content = Fix-FileEnding -Content $content
    
    # Restore Windows line endings if original had them
    if ($originalContent -match '\r\n') {
        $content = $content -replace '(?<!\r)\n', "`r`n"
    }
    
    if ($content -ne $originalContent) {
        if ($DryRun) {
            Write-Host "  [DRY-RUN] Would fix StyleCop warnings" -ForegroundColor Cyan
            return $true
        }
        
        [System.IO.File]::WriteAllText($FilePath, $content, [System.Text.UTF8Encoding]::new($false))
        Write-Host "  [FIXED]" -ForegroundColor Green
        return $true
    }
    
    Write-Host "  [SKIP] No warnings to fix" -ForegroundColor Gray
    return $false
}

# Main script
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "StyleCop Warning Fixer" -ForegroundColor Cyan
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host

if ($DryRun) {
    Write-Host "DRY RUN MODE - No files will be modified" -ForegroundColor Yellow
    Write-Host
}

if (-not (Test-Path $Path)) {
    Write-Error "Path not found: $Path"
    exit 1
}

$files = Get-ChildItem -Path $Path -Filter "*.cs" -Recurse | Where-Object { 
    $_.FullName -notmatch "\\obj\\" -and 
    $_.FullName -notmatch "\\bin\\"
}

Write-Host "Found $($files.Count) C# files in $Path" -ForegroundColor Cyan
Write-Host

$fixedCount = 0
$skippedCount = 0
$errorCount = 0

foreach ($file in $files) {
    $relativePath = $file.FullName.Replace((Get-Location).Path, "").TrimStart([char]92, [char]47)
    Write-Host "[Processing] $relativePath" -ForegroundColor White
    
    try {
        $fixed = Fix-StyleCopWarnings -FilePath $file.FullName -DryRun:$DryRun
        if ($fixed) {
            $fixedCount++
        } else {
            $skippedCount++
        }
    }
    catch {
        Write-Host "  [ERROR] $_" -ForegroundColor Red
        $errorCount++
    }
}

Write-Host
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "Summary:" -ForegroundColor Cyan
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "  Total files:     $($files.Count)" -ForegroundColor White
Write-Host "  Fixed:           $fixedCount" -ForegroundColor Green
Write-Host "  Skipped:         $skippedCount" -ForegroundColor Gray
Write-Host "  Errors:          $errorCount" -ForegroundColor Red

if ($DryRun) {
    Write-Host
    Write-Host "This was a DRY RUN. Run without -DryRun to apply changes." -ForegroundColor Yellow
}

Write-Host ("=" * 80) -ForegroundColor Cyan

exit $errorCount
