"""Reproduce a deliberately simplified four-analyte teaching illustration.
Gaussian signals are invented; these are not the 24-condition screening results.
Run from any directory with Python 3; no third-party packages required.
"""
from pathlib import Path
import csv
import math

BASE = Path(__file__).resolve().parent.parent
DATA = [
    ("A", "C18 | aqueous pH 4.8 | ACN", [4.00, 4.08, 6.00, 1.50]),
    ("B", "Phenyl-hexyl | aqueous pH 4.8 | ACN", [4.80, 4.10, 6.00, 1.50]),
    ("C", "Phenyl-hexyl | aqueous pH 10.0 | ACN", [6.00, 5.00, 5.12, 0.65]),
    ("D", "Phenyl-hexyl | aqueous pH 4.8 | MeOH", [4.00, 4.70, 6.40, 1.70]),
]
NAMES = ["API", "Imp-B", "Deg-1", "Deg-2"]
COLORS = ["#087f8c", "#b34f00", "#7651a8", "#297b36"]
HEIGHTS = [1.0, 0.70, 0.60, 0.50]
SIGMA = 0.10
T_M = 0.50
OUT = BASE / "images/screening/annotated-chromatograms.svg"
OUT.parent.mkdir(parents=True, exist_ok=True)
with (BASE / "data/illustrative-peak-parameters.csv").open("w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["panel", "condition", "analyte", "tR_min", "sigma_min", "relative_height", "tM_min"])
    for panel, condition, times in DATA:
        for name, time, height in zip(NAMES, times, HEIGHTS):
            writer.writerow([panel, condition, name, time, SIGMA, height, T_M])
svg = ['''<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1580" viewBox="0 0 1200 1185" role="img" aria-labelledby="title desc">
<title id="title">Four simulated chromatograms: surface, pH and modifier comparisons</title>
<desc id="desc">A: API and Imp-B overlap on C18. B: phenyl-hexyl separates them and reverses their order. C: changing the aqueous pH moves Deg-2 near the hold-up marker and creates a new Imp-B–Deg-1 overlap. D: changing to methanol reverses the API–Imp-B order relative to B. Colored dashed curves show known simulated components; the black trace is their sum.</desc>
<style>text{font-family:Arial,sans-serif;fill:#17324b;font-size:18px}.head{font-size:28px;font-weight:700}.bold{font-size:22px;font-weight:700}.small{font-size:16px}.axis{stroke:#627386;stroke-width:1.2;fill:none}</style>
<rect width="1200" height="1185" fill="#f5f8fa"/>
<text x="30" y="40" class="head">Follow identities, not peak numbers</text>
<text x="30" y="72">SIMULATED • four-analyte illustration • independent of the 24-condition results table</text>
<text x="30" y="103">Black: total detector signal. Colored dashed curves: known components used to build the simulation.</text>''']
for j, (name, color) in enumerate(zip(NAMES, COLORS)):
    x = 70 + j * 220
    svg.append(f'<path d="M{x} 131 h40" stroke="{color}" stroke-width="3" stroke-dasharray="6 4"/><text x="{x+50}" y="137">{name}</text>')
notes = ["API + Imp-B overlap", "Order reversal: Imp-B before API", "New overlap: Imp-B + Deg-1; Deg-2 near tM", "Modifier changes order relative to B"]
for i, (panel, condition, times) in enumerate(DATA):
    top = 158 + i * 235
    baseline = top + 178
    svg.append(f'<rect x="25" y="{top}" width="1150" height="225" rx="10" fill="white"/>')
    svg.append(f'<text x="45" y="{top+29}" class="bold">{panel} — {condition}</text>')
    svg.append(f'<text x="45" y="{top+55}" class="small">{notes[i]}</text>')
    def x(t): return 105 + 128 * t
    def y(signal): return baseline - 78 * signal
    def path(values): return " ".join(("M" if k==0 else "L") + f"{x(k/100):.2f},{y(v):.2f}" for k,v in enumerate(values))
    curves = [[height*math.exp(-0.5*((k/100-time)/SIGMA)**2) for k in range(801)] for time,height in zip(times,HEIGHTS)]
    svg.append(f'<path d="M105 {baseline-112} V{baseline} H1129" class="axis"/>')
    svg.append(f'<path d="M{x(T_M)} {baseline-112} V{baseline}" stroke="#87919a" stroke-dasharray="3 4"/><text x="{x(T_M)-8}" y="{baseline-117}" class="small">tM</text>')
    for curve,color in zip(curves,COLORS):
        svg.append(f'<path d="{path(curve)}" fill="none" stroke="{color}" stroke-width="2.5" stroke-dasharray="5 4"/>')
    svg.append(f'<path d="{path([sum(v) for v in zip(*curves)])}" fill="none" stroke="#172330" stroke-width="2"/>')
    for tick in range(9):
        svg.append(f'<path d="M{x(tick)} {baseline} v5" class="axis"/><text x="{x(tick)-5}" y="{baseline+23}" class="small">{tick}</text>')
    svg.append(f'<text x="850" y="{baseline+43}" class="small">Retention time (min)</text>')
    for k,(name,t,color) in enumerate(zip(NAMES,times,COLORS)):
        offset = -28 if (i in [0,2] and k==1) else 0
        label_y = y(HEIGHTS[k])-12 + offset
        svg.append(f'<text x="{x(t)+6}" y="{label_y}" style="fill:{color}" class="small">{name}</text>')
svg.append('''<text x="30" y="1130" class="small">Same time and signal scales; all component widths fixed (σ = 0.10 min). Signal heights enlarged for teaching.</text>
<text x="30" y="1158" class="small">No fitted retention model, actual gradient or molecular-mechanism claim. pH 10 requires compatible material.</text></svg>''')
OUT.write_text("\n".join(svg))
