"""Constructed teaching models. Recompute CSVs using the Python standard library.
Run: python3 recompute.py
"""
import csv
import math
from pathlib import Path
ROOT = Path(__file__).resolve().parent

def write(name, fields, rows):
    with (ROOT / name).open('w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader()
        w.writerows(rows)

def calc(ph):
    amine_neutral = 1 / (1 + 10 ** (8.8 - ph))
    phenol_neutral = 1 / (1 + 10 ** (ph - 10.2))
    deg_neutral = 1 / (1 + 10 ** (ph - 4.2))
    return dict(aqueous_pH=round(ph, 2),
                api_amine_unprotonated_fraction=amine_neutral,
                api_phenol_protonated_fraction=phenol_neutral,
                api_fully_uncharged_fraction_independent_sites=amine_neutral * phenol_neutral,
                api_logD_base_only=2.9 + math.log10(amine_neutral),
                api_logD_independent_sites=2.9 + math.log10(amine_neutral * phenol_neutral),
                deg2_neutral_fraction=deg_neutral,
                deg2_logD_assumed_logP_1_5=1.5 + math.log10(deg_neutral))
rows = [calc(i / 100) for i in range(200, 1201, 5)]
write('logd-vs-ph.csv', list(rows[0]), rows)
points = [calc(ph) for ph in [2.7, 4.8, 8.8, 9.5, 10.0, 10.2, 10.8]]
write('screening-ph-summary.csv', list(points[0]), points)
rule = []
for offset in [-2, -1, 0, 1, 2]:
    rule.append(dict(pH_minus_site_pKa=offset,
                     acid_deprotonated_percent=100 / (1 + 10 ** (-offset)),
                     base_unprotonated_percent=100 / (1 + 10 ** (-offset)),
                     buffer_capacity_relative_to_maximum=4 * 10 ** offset / (1 + 10 ** offset) ** 2))
write('ionization-buffer-rule.csv', list(rule[0]), rule)
recipes = []
for name, mmol, mw in [('total_formate_from_formic_acid', 40, 46.03),
                       ('total_acetate_from_acetic_acid', 10, 60.052),
                       ('starting_ammonium_bicarbonate', 10, 79.056)]:
    recipes.append(dict(recipe=name, final_aqueous_volume_L=1,
                        starting_amount_mmol=mmol, molar_mass_g_per_mol=mw,
                        pure_equivalent_mass_g=mmol * mw / 1000))
write('buffer-recipes.csv', list(recipes[0]), recipes)
write('gradient-buffer-dilution.csv', ['organic_B_percent', 'buffer_in_A_mM', 'nominal_delivered_buffer_mM'],
      [dict(organic_B_percent=b, buffer_in_A_mM=10, nominal_delivered_buffer_mM=10 * (1-b/100)) for b in [5, 50, 95]])
assert abs(calc(8.8)['api_logD_base_only'] - (2.9-math.log10(2))) < 1e-12
assert abs(calc(9.5)['api_fully_uncharged_fraction_independent_sites'] - 0.694993) < 1e-6
assert all(0 < r['api_fully_uncharged_fraction_independent_sites'] < 1 for r in rows)
print('Recomputed five CSVs; half-ionization and two-site checks passed.')
