"""Optional figure redraw; numerical reproduction does not require Matplotlib.
Install the pinned optional environment in docs/FIGURES.md, then run this file.
"""
import json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

root = Path(__file__).resolve().parents[1]
result = json.loads((root / 'reference/results.json').read_text(encoding='utf-8'))
plt.rcParams.update({'font.size': 10, 'svg.fonttype': 'none', 'svg.hashsalt': 'ligninqc-1.0.0', 'axes.spines.top': False, 'axes.spines.right': False})
fig, axes = plt.subplots(1, 3, figsize=(14, 4.4), constrained_layout=True)
for ax, key, label in zip(axes[:2], ['dpph_neutral_all','abts_carboxylate_all'], ['DPPH · neutral forms','ABTS · carboxylate-matched forms']):
 a = result['lauberte2019']['analyses'][key]
 x = [p['x'] for p in a['points']]
 y = [p['y'] for p in a['points']]
 ax.scatter(x,y,color='#007c78',s=40,zorder=3,edgecolors='white',linewidths=.6)
 domain = [min(x),max(x)]
 ax.plot(domain, [a['intercept']+a['slope']*v for v in domain], color='#007c78',linewidth=1.4,label='OLS, all available pairs')
 for p in a['points']:
  if p['id'] in ('5','6','16'):
   ax.annotate(p['id'],(p['x'],p['y']),xytext=(5,5),textcoords='offset points',fontsize=9)
 ax.set(xlabel='O–H BDE (kcal/mol)',ylabel='RDI per model-compound molecule',title=f"{label}\nn={a['n']}; R²={a['r_squared']:.3f}")
 ax.grid(alpha=.18)
 ax.legend(frameon=False,fontsize=8,loc='upper right')
r = result['kazachenko2022']['full_table']['rows']
axes[2].axhline(0,color='#263b43',linewidth=1)
axes[2].bar([p['index'] for p in r],[p['right_minus_left'] for p in r],width=34,color=['#ae5800' if p['right_minus_left']<0 else '#007c78' for p in r])
axes[2].set(xlabel='Temperature (°C)',ylabel='Mass loss: sulfated − initial (percentage points)',title='Thermal comparison · Table 2\nArgon; heating rate 10 °C/min')
axes[2].grid(axis='y',alpha=.18)
axes[2].set_xticks([200,300,400,500,600,700,800])
fig.suptitle('Reanalysis of rounded published data: Lauberte et al. 2019 and Kazachenko et al. 2022',fontsize=12)
out = root / 'reference/figures'
out.mkdir(parents=True,exist_ok=True)
fig.savefig(out/'published-data-reanalysis.svg',metadata={'Date':None,'Creator':'LigninQC; Matplotlib','Description':'Published aggregate data only; no new DFT or experimental data.'})
fig.savefig(out/'published-data-reanalysis.png',dpi=180,metadata={'Software':'LigninQC; Matplotlib'})
fig.savefig(out/'published-data-reanalysis.pdf',metadata={'CreationDate':None,'ModDate':None,'Creator':'LigninQC; Matplotlib'})
