param(
    [string]$FilePath
)

Write-Host "Processing: $FilePath"

$lines = Get-Content -Path $FilePath -Encoding UTF8
Write-Host "Total lines: $($lines.Count)"

$outputLines = [System.Collections.Generic.List[string]]::new()
$insideArray = $false
$skippedCount = 0

foreach ($i in 0..($lines.Count - 1)) {
    $line = $lines[$i]
    $trimmed = $line.Trim()
    
    # Detect the start of the return array
    if (-not $insideArray -and $trimmed -eq 'return [') {
        $insideArray = $true
        $outputLines.Add($line)
        continue
    }
    
    if (-not $insideArray) {
        # Before the array: keep everything
        $outputLines.Add($line)
        continue
    }
    
    # Inside the array:
    
    # Skip premature ]; closings
    if ($trimmed -eq '];') {
        Write-Host "  Skipping premature ]; at line $($i + 1)"
        $skippedCount++
        continue
    }
    
    # Skip ?> tags
    if ($trimmed -eq '?>' -or $trimmed -eq '?>') {
        Write-Host "  Skipping ?> at line $($i + 1)"
        $skippedCount++
        continue
    }
    
    # Keep everything else
    $outputLines.Add($line)
}

# Add the single final ];
$outputLines.Add('];')

Write-Host "Skipped $skippedCount premature closings"
Write-Host "Output lines: $($outputLines.Count)"

# Write the fixed content
$outputLines | Set-Content -Path $FilePath -Encoding UTF8

Write-Host "File written successfully!"
Write-Host ""
