"""Original Bopbun example; code and synthetic observations: CC0-1.0."""
from pathlib import Path
import csv
import json
import platform
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

OUT = Path(__file__).resolve().parent
plt.rcdefaults()
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 11,
                     'figure.autolayout': False, 'figure.constrained_layout.use': False,
                     'savefig.bbox': None})
x = [0, 1, 2, 3, 4]
series = {'A': [2, 5, 4, 7, 6], 'B': [0.0002, 0.0005, 0.0004, 0.0007, 0.0006]}
rows = []
with (OUT / 'synthetic.csv').open('w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['time_h', 'series_A', 'series_B'])
    w.writerows(zip(x, series['A'], series['B']))
for stage in ['before', 'after']:
    for name, y in series.items():
        fig, ax = plt.subplots(figsize=(5, 3.2), dpi=200, layout=None)
        ax.plot(x, y, 'o-', color='#007C83', linewidth=1.8)
        ax.set(xlabel='Time (h)', ylabel='Response (a.u.)', title=f'Series {name}', xlim=(-0.2, 4.2))
        factor = 1 if name == 'A' else 0.0001
        ax.set_ylim(0, 8 * factor)
        ax.set_yticks([v * factor for v in [0, 2, 4, 6, 8]])
        ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f' if name == 'A' else '%.4f'))
        ax.set_xticks(x)
        ax.grid(axis='y', color='#dddddd')
        if stage == 'before':
            fig.tight_layout(pad=1.2)
        else:
            fig.subplots_adjust(left=0.25, right=0.96, bottom=0.20, top=0.88)
        fig.canvas.draw()
        box = ax.get_window_extent()
        rows.append({'stage': stage, 'series': name, 'left_px': box.x0,
                     'bottom_px': box.y0, 'width_px': box.width, 'height_px': box.height})
        fig.savefig(OUT / f'{stage}-{name}.png', dpi=200, bbox_inches=None)
        if stage == 'after':
            fig.savefig(OUT / f'{stage}-{name}.pdf', bbox_inches=None, metadata={'CreationDate': None, 'ModDate': None})
        plt.close(fig)
with (OUT / 'positions.csv').open('w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0]))
    w.writeheader()
    w.writerows(rows)
(OUT / 'runtime.json').write_text(json.dumps({'python': platform.python_version(),
    'matplotlib': matplotlib.__version__, 'backend': matplotlib.get_backend(),
    'font': 'DejaVu Sans', 'canvas_px': [1000, 640], 'positions': rows}, indent=2), encoding='utf-8')
print(json.dumps(rows))
