$ErrorActionPreference = 'Stop'
$ModRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$LogFile = Join-Path $ModRoot 'Compile.log'
"RDF Genes compile log - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Set-Content -Path $LogFile -Encoding UTF8
function Log([string]$Text = '') { Write-Host $Text; $Text | Add-Content -Path $LogFile -Encoding UTF8 }
function Fail([string]$Text, [int]$Code = 1) { Log ''; Log "[ERROR] $Text"; Log ''; Log "Mod folder: $ModRoot"; Log "Log file  : $LogFile"; exit $Code }
try {
  Log '============================================================'
  Log ' RDF Genes v1.0.4p Performance Pass - compile RDFGenes.dll for RimWorld 1.6'
  Log '============================================================'; Log ''
  $ModsDir = Split-Path -Parent $ModRoot
  $RimWorld = Split-Path -Parent $ModsDir
  $Managed = Join-Path $RimWorld 'RimWorldWin64_Data\Managed'
  $AssemblyCSharp = Join-Path $Managed 'Assembly-CSharp.dll'
  if (-not (Test-Path $AssemblyCSharp)) { Fail "Could not find Assembly-CSharp.dll at '$AssemblyCSharp'. Put the RDF_Genes folder directly inside RimWorld\Mods before compiling." }
  $Candidates = @("$env:WINDIR\Microsoft.NET\Framework64\v4.0.30319\csc.exe", "$env:WINDIR\Microsoft.NET\Framework\v4.0.30319\csc.exe")
  $CSC = $Candidates | Where-Object { Test-Path $_ } | Select-Object -First 1
  if (-not $CSC) { $Cmd = Get-Command csc.exe -ErrorAction SilentlyContinue; if ($Cmd) { $CSC = $Cmd.Source } }
  if (-not $CSC) { Fail 'csc.exe was not found.' }
  $Harmony = Get-ChildItem -Path $ModsDir -Filter '0Harmony.dll' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName
  if (-not $Harmony) { Fail "Could not find 0Harmony.dll anywhere below '$ModsDir'. Make sure Harmony is installed." }
  $Sources = Get-ChildItem -Path (Join-Path $ModRoot 'Source\RDFGenes') -Filter '*.cs' -File -Recurse | Select-Object -ExpandProperty FullName
  if (-not $Sources) { Fail 'No C# source files were found.' }
  $OutDir = Join-Path $ModRoot '1.6\Assemblies'; New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
  $Output = Join-Path $OutDir 'RDFGenes.dll'
  $References = @($AssemblyCSharp, $Harmony)

  # RimWorld 1.6 assemblies expose several System.Span / ReadOnlySpan signatures.
  # The legacy .NET Framework csc.exe used by this local compiler therefore also
  # needs the same netstandard facade that RimWorld/Unity ships with.
  $NetStandardCandidates = @(
    (Join-Path $Managed 'netstandard.dll'),
    (Join-Path $Managed 'Facades\netstandard.dll'),
    (Join-Path $RimWorld 'MonoBleedingEdge\lib\mono\4.5\Facades\netstandard.dll'),
    (Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\Facades\netstandard.dll'),
    (Join-Path $env:WINDIR 'Microsoft.NET\Framework\v4.0.30319\Facades\netstandard.dll')
  )
  $NetStandard = $NetStandardCandidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1
  if (-not $NetStandard) {
    $NetStandard = Get-ChildItem -Path $RimWorld -Filter 'netstandard.dll' -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName
  }
  if (-not $NetStandard) { Fail 'Could not find netstandard.dll. RimWorld 1.6 requires this reference for System.Span/ReadOnlySpan signatures.' }
  $References += $NetStandard

  $UnityCore = Join-Path $Managed 'UnityEngine.CoreModule.dll'; if (Test-Path $UnityCore) { $References += $UnityCore }
  $UnityLegacy = Join-Path $Managed 'UnityEngine.dll'; if (Test-Path $UnityLegacy) { $References += $UnityLegacy }
  Log "RimWorld : $RimWorld"; Log "Compiler : $CSC"; Log "Harmony  : $Harmony"; Log "netstd   : $NetStandard"; Log "Output   : $Output"; Log ''
  foreach ($S in $Sources) { Log "Source   : $S" }
  Log ''
  $Args = @('/nologo','/target:library','/optimize+',"/out:$Output")
  foreach ($Ref in $References) { $Args += "/reference:$Ref" }
  foreach ($S in $Sources) { $Args += $S }
  Log 'Compiler output:'; Log '----------------'
  $CompilerOutput = & $CSC $Args 2>&1; $ExitCode=$LASTEXITCODE
  foreach ($Line in $CompilerOutput) { Log ([string]$Line) }
  Log '----------------'
  if ($ExitCode -ne 0) { Fail "Compilation failed with compiler exit code $ExitCode." $ExitCode }
  if (-not (Test-Path $Output)) { Fail 'Compiler returned success but RDFGenes.dll was not created.' }
  Log ''; Log '[OK] RDFGenes.dll compiled successfully.'; Log 'Run FINAL_CHECKLIST.txt in game.'; Log ''; Log "DLL: $Output"; exit 0
} catch { Log ''; Log '[UNEXPECTED ERROR]'; Log $_.Exception.ToString(); Log ''; Log "Upload this file to ChatGPT: $LogFile"; exit 99 }
