<#
.SYNOPSIS
  Renders Fig1 and Fig2 as 600 dpi TIFF files sized for a Springer single-column text area (174 mm).
.DESCRIPTION
  Uses System.Drawing so no external converter is required. Reads the already-computed statistics in
  runs\<run>\tables\ so nothing is recalculated and the figures cannot drift from the reported numbers.
  Greyscale-safe: series are distinguished by fill pattern as well as shade.
.EXAMPLE
  .\New-FiguresTiff.ps1 -RunDir ..\runs\ai-retractions -OutDir ..\papers\ai-retractions\figures
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)][string]$RunDir,
    [Parameter(Mandatory = $true)][string]$OutDir,
    [int]$Dpi = 600,
    [double]$WidthMm = 174,
    [int]$FirstYear = 2010,
    [int]$LastYear = 2025,
    [int]$MaxDaysDisplay = 3000
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null

$scale = $Dpi / 96.0
function Save-Tiff {
    param([System.Drawing.Bitmap]$Bmp, [string]$Path)
    $codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/tiff' }
    $p = New-Object System.Drawing.Imaging.EncoderParameters 1
    $p.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Compression), ([int][System.Drawing.Imaging.EncoderValue]::CompressionLZW)
    $Bmp.Save($Path, $codec, $p)
}
function New-Canvas {
    param([int]$WPx, [int]$HPx)
    $bmp = New-Object System.Drawing.Bitmap $WPx, $HPx
    $bmp.SetResolution($Dpi, $Dpi)
    $g = [System.Drawing.Graphics]::FromImage($bmp)
    $g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
    $g.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
    $g.Clear([System.Drawing.Color]::White)
    return @($bmp, $g)
}

# ---------------- Fig 1 ----------------
$rows = @(Import-Csv (Join-Path $RunDir 'tables\stats_by_year_ci.csv') |
    Where-Object { [int]$_.Year -ge $FirstYear -and [int]$_.Year -le $LastYear } | Sort-Object { [int]$_.Year })
$W = [int](660 * $scale); $H = [int](400 * $scale)
$c = New-Canvas $W $H; $bmp = $c[0]; $g = $c[1]
$L = 62 * $scale; $R = 58 * $scale; $T = 24 * $scale; $B = 58 * $scale
$pw = $W - $L - $R; $ph = $H - $T - $B
$fontAxis = New-Object System.Drawing.Font('Arial', (9 * $scale), [System.Drawing.FontStyle]::Regular, [System.Drawing.GraphicsUnit]::Pixel)
$fontLab = New-Object System.Drawing.Font('Arial', (11 * $scale), [System.Drawing.FontStyle]::Regular, [System.Drawing.GraphicsUnit]::Pixel)
$black = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::Black)
$grey = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(184, 184, 184))
$penThin = New-Object System.Drawing.Pen ([System.Drawing.Color]::FromArgb(200, 200, 200)), (0.6 * $scale)
$penAxis = New-Object System.Drawing.Pen ([System.Drawing.Color]::Black), (1.1 * $scale)
$penEdge = New-Object System.Drawing.Pen ([System.Drawing.Color]::FromArgb(85, 85, 85)), (0.6 * $scale)
$penLine = New-Object System.Drawing.Pen ([System.Drawing.Color]::Black), (1.8 * $scale)
$penLine.DashPattern = @(4.0, 2.5)
$hatch = New-Object System.Drawing.Drawing2D.HatchBrush ([System.Drawing.Drawing2D.HatchStyle]::ForwardDiagonal), ([System.Drawing.Color]::Black), ([System.Drawing.Color]::White)
$sfRight = New-Object System.Drawing.StringFormat; $sfRight.Alignment = [System.Drawing.StringAlignment]::Far
$sfCentre = New-Object System.Drawing.StringFormat; $sfCentre.Alignment = [System.Drawing.StringAlignment]::Center
$sfLeft = New-Object System.Drawing.StringFormat; $sfLeft.Alignment = [System.Drawing.StringAlignment]::Near

$maxAll = ($rows | Measure-Object AllRetractions -Maximum).Maximum
$yMax = [Math]::Ceiling($maxAll / 2000.0) * 2000
for ($v = 0; $v -le $yMax; $v += 2000) {
    $y = $T + $ph - ($v / [double]$yMax) * $ph
    $g.DrawLine($penThin, $L, $y, $L + $pw, $y)
    $g.DrawString("$v", $fontAxis, $black, ($L - 6 * $scale), ($y - 6 * $scale), $sfRight)
}
for ($v = 0; $v -le 50; $v += 10) {
    $y = $T + $ph - ($v / 50.0) * $ph
    $g.DrawString("$v", $fontAxis, $black, ($L + $pw + 6 * $scale), ($y - 6 * $scale), $sfLeft)
}
$n = $rows.Count; $slot = $pw / $n; $bw = [Math]::Min(18 * $scale, $slot * 0.36)
$pts = New-Object System.Collections.ArrayList
$i = 0
foreach ($r in $rows) {
    $cx = $L + $slot * $i + $slot / 2.0
    $hAll = ([double]$r.AllRetractions / $yMax) * $ph
    $hMac = ([double]$r.MachineAttributed / $yMax) * $ph
    $g.FillRectangle($grey, ($cx - $bw - 1 * $scale), ($T + $ph - $hAll), $bw, $hAll)
    $g.DrawRectangle($penEdge, ($cx - $bw - 1 * $scale), ($T + $ph - $hAll), $bw, $hAll)
    $g.FillRectangle($hatch, ($cx + 1 * $scale), ($T + $ph - $hMac), $bw, $hMac)
    $g.DrawRectangle($penEdge, ($cx + 1 * $scale), ($T + $ph - $hMac), $bw, $hMac)
    $st = $g.Save()
    $g.TranslateTransform($cx, ($T + $ph + 8 * $scale)); $g.RotateTransform(-45)
    $g.DrawString($r.Year, $fontAxis, $black, 0, 0, $sfRight)
    $g.Restore($st)
    [void]$pts.Add((New-Object System.Drawing.PointF $cx, ($T + $ph - ([double]$r.SharePct / 50.0) * $ph)))
    $i++
}
$g.DrawLines($penLine, [System.Drawing.PointF[]]$pts.ToArray())
foreach ($p in $pts) { $g.FillEllipse($black, ($p.X - 2.6 * $scale), ($p.Y - 2.6 * $scale), (5.2 * $scale), (5.2 * $scale)) }
$g.DrawLine($penAxis, $L, ($T + $ph), ($L + $pw), ($T + $ph))
$g.DrawLine($penAxis, $L, $T, $L, ($T + $ph))
$g.DrawLine($penAxis, ($L + $pw), $T, ($L + $pw), ($T + $ph))
$st = $g.Save(); $g.TranslateTransform((16 * $scale), ($T + $ph / 2)); $g.RotateTransform(-90)
$g.DrawString('Retractions per year', $fontLab, $black, 0, 0, $sfCentre); $g.Restore($st)
$st = $g.Save(); $g.TranslateTransform(($W - 14 * $scale), ($T + $ph / 2)); $g.RotateTransform(-90)
$g.DrawString('Machine-attributed share (%)', $fontLab, $black, 0, 0, $sfCentre); $g.Restore($st)
$g.DrawString('Retraction year', $fontLab, $black, ($L + $pw / 2), ($H - 20 * $scale), $sfCentre)
$lx = $L + 16 * $scale; $ly = $T + 6 * $scale; $sw = 14 * $scale; $sh = 10 * $scale
$g.FillRectangle($grey, $lx, $ly, $sw, $sh); $g.DrawRectangle($penEdge, $lx, $ly, $sw, $sh)
$g.DrawString('All retractions', $fontAxis, $black, ($lx + $sw + 5 * $scale), ($ly - 1 * $scale), $sfLeft)
$g.FillRectangle($hatch, $lx, ($ly + 16 * $scale), $sw, $sh); $g.DrawRectangle($penEdge, $lx, ($ly + 16 * $scale), $sw, $sh)
$g.DrawString('Machine-attributed', $fontAxis, $black, ($lx + $sw + 5 * $scale), ($ly + 15 * $scale), $sfLeft)
$g.DrawLine($penLine, $lx, ($ly + 36 * $scale), ($lx + $sw), ($ly + 36 * $scale))
$g.DrawString('Share of all retractions', $fontAxis, $black, ($lx + $sw + 5 * $scale), ($ly + 30 * $scale), $sfLeft)
$g.Dispose()
Save-Tiff -Bmp $bmp -Path (Join-Path $OutDir 'Fig1.tif'); $bmp.Dispose()
Write-Host ("Wrote Fig1.tif  ({0} x {1} px at {2} dpi)" -f $W, $H, $Dpi) -ForegroundColor Green

# ---------------- Fig 2 ----------------
$box = @(Import-Csv (Join-Path $RunDir 'tables\fig2_boxstats.csv'))
$W2 = [int](660 * $scale); $H2 = [int](300 * $scale)
$c2 = New-Canvas $W2 $H2; $bmp2 = $c2[0]; $g2 = $c2[1]
$L2 = 148 * $scale; $R2 = 26 * $scale; $T2 = 26 * $scale; $B2 = 54 * $scale
$pw2 = $W2 - $L2 - $R2; $ph2 = $H2 - $T2 - $B2
$fill = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(232, 232, 232))
$penBox = New-Object System.Drawing.Pen ([System.Drawing.Color]::Black), (1.1 * $scale)
$penMed = New-Object System.Drawing.Pen ([System.Drawing.Color]::Black), (2.6 * $scale)
for ($v = 0; $v -le $MaxDaysDisplay; $v += 500) {
    $x = $L2 + ($v / [double]$MaxDaysDisplay) * $pw2
    $g2.DrawLine($penThin, $x, $T2, $x, ($T2 + $ph2))
    $g2.DrawString("$v", $fontAxis, $black, $x, ($T2 + $ph2 + 6 * $scale), $sfCentre)
}
$row = 0
foreach ($b in $box) {
    $cy = $T2 + $ph2 * (0.3 + 0.42 * $row)
    $bh = 36 * $scale
    $fx = { param($val) $L2 + ([Math]::Min([double]$val, $MaxDaysDisplay) / [double]$MaxDaysDisplay) * $pw2 }
    $x1 = & $fx $b.Q1; $x3 = & $fx $b.Q3; $xm = & $fx $b.Med; $xl = & $fx $b.P5; $xh = & $fx $b.P95
    $g2.DrawLine($penBox, $xl, $cy, $xh, $cy)
    foreach ($xw in @($xl, $xh)) { $g2.DrawLine($penBox, $xw, ($cy - 8 * $scale), $xw, ($cy + 8 * $scale)) }
    if ($row -eq 0) { $g2.FillRectangle($hatch, $x1, ($cy - $bh / 2), ($x3 - $x1), $bh) }
    else { $g2.FillRectangle($fill, $x1, ($cy - $bh / 2), ($x3 - $x1), $bh) }
    $g2.DrawRectangle($penBox, $x1, ($cy - $bh / 2), ($x3 - $x1), $bh)
    $g2.DrawLine($penMed, $xm, ($cy - $bh / 2), $xm, ($cy + $bh / 2))
    $g2.DrawString($b.Name, $fontLab, $black, ($L2 - 8 * $scale), ($cy - 14 * $scale), $sfRight)
    $g2.DrawString(("n = " + $b.N), $fontAxis, $black, ($L2 - 8 * $scale), ($cy + 2 * $scale), $sfRight)
    $row++
}
$g2.DrawLine($penAxis, $L2, ($T2 + $ph2), ($L2 + $pw2), ($T2 + $ph2))
$g2.DrawString(("Time from publication to retraction (days), truncated at " + $MaxDaysDisplay), $fontLab, $black, ($L2 + $pw2 / 2), ($H2 - 22 * $scale), $sfCentre)
$g2.Dispose()
Save-Tiff -Bmp $bmp2 -Path (Join-Path $OutDir 'Fig2.tif'); $bmp2.Dispose()
Write-Host ("Wrote Fig2.tif  ({0} x {1} px at {2} dpi)" -f $W2, $H2, $Dpi) -ForegroundColor Green
Get-ChildItem $OutDir -Filter *.tif | ForEach-Object { "  {0}  {1:N1} MB" -f $_.Name, ($_.Length / 1MB) }
