"""Draw the pH-solubility figure as an SVG in the same card style as the Week 8
'Know the Molecule' log D figure, so Compound X looks the same in both weeks.

Reads ph-solubility.csv, sink-conditions.csv and salt-constants.csv (written by
recompute.py) and writes ../images/solubility/ph-solubility-and-sink.svg.
Standard library only. No values are experimental observations.
"""
import csv, math, os

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', 'solubility', 'ph-solubility-and-sink.svg')

def rows(name):
    with open(os.path.join(HERE, name), newline='') as f:
        return list(csv.DictReader(f))

curve = [(float(r['pH']), float(r['solubility_mg_mL_as_free_base'])) for r in rows('ph-solubility.csv')]
const = rows('salt-constants.csv')[0]
pka, phmax = float(const['pKa']), float(const['pHmax'])
# extend the free-base branch past pH 10 to match the Week 8 axis: S = S0(1 + 10^(pKa - pH))
s0 = float(const['intrinsic_free_base_solubility_mg_mL'])
curve += [(round(10.0 + 0.1 * i, 1), s0 * (1 + 10 ** (pka - (10.0 + 0.1 * i)))) for i in range(1, 21)]
hcl = next(r for r in rows('sink-conditions.csv') if r['medium'] == '0.1 N HCl')
s_hcl, ph_hcl = float(hcl['solubility_mg_mL']), float(hcl['pH'])
sink = 3 * float(const['tablet_free_base_mg']) / 900.0  # mg/mL for 3x sink in 900 mL

# Plot frame matches the Week 8 card: x 125-735, y 280-550 (same palette and fonts)
X0, X1, PH0, PH1 = 125, 735, 1.0, 12.0
Y0, Y1, L0, L1 = 280, 550, 2.0, -2.0          # log10(mg/mL): 100 at top, 0.01 at bottom
x = lambda ph: X0 + (ph - PH0) * (X1 - X0) / (PH1 - PH0)
y = lambda s: Y0 + (L0 - math.log10(s)) * (Y1 - Y0) / (L0 - L1)

TEAL, ORANGE, GUIDE = '#006575', '#b5491a', '#607587'
o = []
o.append('<svg xmlns="http://www.w3.org/2000/svg" width="1490" height="1130" viewBox="40 142 745 565" role="img" aria-labelledby="title desc">')
o.append('<title id="title">Compound X hydrochloride: solubility versus pH</title>')
o.append(f'<desc id="desc">Calculated solubility of Compound X hydrochloride on a log scale from pH 1 to 12: a salt-limited plateau near {curve[0][1]:.0f} mg/mL below pHmax {phmax:.1f}, a free-base-limited fall above it that flattens near the amine pKa {pka}, a lower common-ion point of {s_hcl:.1f} mg/mL in 0.1 N HCl, and a 3x sink line at {sink:.3f} mg/mL.</desc>')
o.append('<style>text{font-family:Arial,sans-serif;fill:#16324b} .head{font-size:27px;font-weight:700}.small{font-size:20px}.axis{fill:none;stroke:#40596e;stroke-width:2.5}.grid{fill:none;stroke:#c4d0d9;stroke-width:1.5}</style>')
o.append('<rect x="40" y="142" width="745" height="565" fill="#f6f9fb"/>')
o.append('<rect x="40" y="142" width="745" height="565" rx="18" fill="white"/>')
o.append('<text x="65" y="186" class="head">SMALL MOLECULE • pKa + solubility</text>')
o.append('<text x="65" y="220" class="small">Calculated equilibrium solubility of the HCl salt, not a rate</text>')
# reference lines: pHmax and pKa, dashed like the pH 3 / pH 10 markers in Week 8
for ph, label in [(phmax, f'pHmax {phmax:.1f}'), (pka, f'pKa {pka}')]:
    o.append(f'<path d="M{x(ph):.0f} {Y0}V{Y1}" fill="none" stroke="{GUIDE}" stroke-width="2" stroke-dasharray="6 7"/>'
             f'<text x="{x(ph):.0f}" y="{Y0 - 8}" class="small" text-anchor="middle">{label}</text>')
for v, lab in [(100, '100'), (10, '10'), (1, '1'), (0.1, '0.1'), (0.01, '0.01')]:
    o.append(f'<path d="M{X0} {y(v):.1f}H{X1}" class="grid"/><text x="{X0 - 12}" y="{y(v) + 7:.1f}" class="small" text-anchor="end">{lab}</text>')
o.append(f'<path d="M{X0} {Y0 - 20}V{Y1}H{X1}" class="axis"/>')
for ph in [1] + list(range(2, 13, 2)):
    o.append(f'<text x="{x(ph):.0f}" y="580" class="small" text-anchor="middle">{ph}</text>')
o.append(f'<text x="{(X0 + X1) / 2:.0f}" y="610" class="small" text-anchor="middle">Aqueous pH</text>')
o.append('<text x="60" y="250" class="small">mg/mL (log)</text>')
# 3x sink line
o.append(f'<path d="M{X0} {y(sink):.1f}H{X1}" fill="none" stroke="{GUIDE}" stroke-width="2.5" stroke-dasharray="14 8"/>')
o.append(f'<text x="{X0 + 20}" y="{y(sink) - 10:.1f}" class="small">3× sink: {sink:.3f} mg/mL</text>')
# region labels
o.append(f'<text x="{X0 + 80}" y="{y(curve[0][1]) - 14:.1f}" class="small">Salt limited (Ksp)</text>')
o.append(f'<text x="{x(6.5):.0f}" y="{y(0.045):.1f}" class="small">Free-base</text><text x="{x(6.5):.0f}" y="{y(0.045) + 24:.1f}" class="small">limited</text>')
# teal Compound X curve
pts = ' '.join(f'{x(p):.1f},{y(s):.1f}' for p, s in curve)
o.append(f'<polyline points="{pts}" fill="none" stroke="{TEAL}" stroke-width="5"/>')
# common-ion point
cx, cy = x(ph_hcl), y(s_hcl)
o.append(f'<rect x="{cx - 8:.1f}" y="{cy - 8:.1f}" width="16" height="16" fill="{ORANGE}"/>')
o.append(f'<text x="{cx + 18:.1f}" y="{cy + 26:.1f}" class="small">0.1 N HCl: {s_hcl:.1f} mg/mL</text>')
o.append('<text x="90" y="640" class="small">Teal: Compound X·HCl in water, no added chloride</text>')
o.append('<text x="90" y="670" class="small">Orange: same salt in 0.1 N HCl (common-ion effect)</text>')
o.append('</svg>')

with open(OUT, 'w') as f:
    f.write('\n'.join(o) + '\n')
print('wrote', os.path.relpath(OUT))
