# clean_unity.ps1 - Manages Unity files content hashing and change detection
param(
    [string]$Action = "Finish"
)

if (-not (Test-Path "Intermediate")) { New-Item -ItemType Directory -Path "Intermediate" | Out-Null }

$hashFile = "Intermediate\unity_hashes.tmp"

if ($Action -eq "Start") {
    # Compute SHA256 hashes of all existing Unity files before FASTBuild runs
    $hashes = @{}
    Get-ChildItem -Path "Intermediate" -Recurse -Filter "*_Unity*.cpp" -ErrorAction SilentlyContinue | ForEach-Object {
        $hash = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash
        $hashes[$_.FullName] = $hash
    }
    $hashes | ConvertTo-Json | Set-Content -Path $hashFile -ErrorAction SilentlyContinue
}
elseif ($Action -eq "Finish") {
    $oldHashes = @{}
    if (Test-Path $hashFile) {
        try {
            $json = Get-Content $hashFile -Raw -ErrorAction SilentlyContinue
            if ($json) {
                $obj = $json | ConvertFrom-Json
                foreach ($prop in $obj.PSObject.Properties) {
                    $oldHashes[$prop.Name] = $prop.Value
                }
            }
        } catch {}
        Remove-Item $hashFile -ErrorAction SilentlyContinue
    }

    # Clean '#pragma message' from generated Unity files if present
    Get-ChildItem -Path "Intermediate" -Recurse -Filter "*_Unity*.cpp" -ErrorAction SilentlyContinue | ForEach-Object {
        $filePath = $_.FullName
        $lines = [System.IO.File]::ReadAllLines($filePath)
        $filtered = $lines | Where-Object { $_ -notlike '*#pragma message*' }
        if ($lines.Count -ne $filtered.Count) {
            [System.IO.File]::WriteAllLines($filePath, $filtered)
        }
    }

    # Detect if any Unity file is new or has changed content
    $unityChanged = "0"
    $currentFiles = Get-ChildItem -Path "Intermediate" -Recurse -Filter "*_Unity*.cpp" -ErrorAction SilentlyContinue
    if (-not $currentFiles) {
        $unityChanged = "1"
    } else {
        foreach ($file in $currentFiles) {
            $path = $file.FullName
            $newHash = (Get-FileHash -Path $path -Algorithm SHA256).Hash
            if (-not $oldHashes.ContainsKey($path) -or $oldHashes[$path] -ne $newHash) {
                $unityChanged = "1"
                break
            }
        }
    }

    Set-Content -Path "Intermediate\unity_changed.tmp" -Value $unityChanged
}
