"""Camera-ready Table 1, directly from the frozen posterior evaluations.

The original TensorFlow producer is preserved in
paper_data/pac_bayes/experiment/run_safe_table1.py. This short NumPy reader
implements the same statistical calculation; it never trains a model.
"""
from pathlib import Path
import json
import numpy as np
import pandas as pd


def gaussian_kl(k, sigma_q, sigma_p):
    """KL[N(0,sigma_q^2 I_k) || N(0,sigma_p^2 I_k)].

    Taking the Q expectation of log(q/p) gives
    k/2 * [sigma_q^2/sigma_p^2 - 1 + log(sigma_p^2/sigma_q^2)].
    Both distributions live on the same frozen retained affine subspace.
    """
    ratio = (sigma_q / sigma_p) ** 2
    return 0.5 * k * (ratio - 1 - np.log(ratio))


def certificate_from_draws(risks, k, sigma_q, sigma_p, n,
                           delta_pb=0.008, delta_mc=0.002):
    """Separate posterior Monte Carlo uncertainty from the PAC-Bayes term.

    risks[s] is the empirical loss, averaged over all n certificate examples,
    for one independent posterior network. Each entry is in [0,1].
    The empirical-Bernstein upper correction uses the variance ACROSS draws.
    A fixed-prior/fixed-Q Hoeffding PAC-Bayes calculation supplies the PB term;
    the build-only Q and bound parameter are frozen before certificate access.
    Five rows allocate 5*(delta_pb + delta_mc) = 0.05 failure probability.
    """
    risks = np.asarray(risks, dtype=np.float64)
    assert risks.ndim == 1 and len(risks) > 1 and n > 0
    assert np.isfinite(risks).all() and np.all((0 <= risks) & (risks <= 1))
    S = len(risks)
    mean, variance = risks.mean(), risks.var(ddof=1)
    log_mc = np.log(2 / delta_mc)
    mc = np.sqrt(2 * variance * log_mc / S) + 7 * log_mc / (3 * (S - 1))
    kl = gaussian_kl(k, sigma_q, sigma_p)
    pb = np.sqrt((kl + np.log(1 / delta_pb)) / (2 * n))
    return dict(certificate_mean=mean, mc_correction=mc, kl=kl,
                pb_complexity=pb, population_bound=mean + mc + pb)


def reconstruct_table(evidence_dir):
    """Read all 4,096 certificate/test draws per model; check recorded results."""
    experiment = Path(evidence_dir) / 'experiment'
    original = pd.read_csv(experiment / 'safe_table1_simultaneous_95.csv')
    keys = ['mnist_mlp', 'mnist_lenet', 'cifar_resnet32',
            'cifar_wrn16_4', 'cifar_densenet_small']
    rows = []
    for key, saved in zip(keys, original.to_dict('records')):
        directory = experiment / 'rows' / key
        cert = pd.read_csv(directory / 'posterior_certificate_risks.csv')
        test = pd.read_csv(directory / 'audit_only_test_posterior_risks.csv')
        final = json.loads((directory / 'final_certificate.json').read_text())
        assert len(cert) == len(test) == 4096
        terms = certificate_from_draws(
            cert['certificate_clipped_nll_risk'], int(saved['k']),
            saved['sigma_Q'], saved['sigma_P'], int(saved['n_certificate']),
            final['delta_PB_row'], final['delta_MC_row'])
        test_mean = test['audit_only_test_clipped_nll_risk'].mean()
        np.testing.assert_allclose(
            [terms['population_bound'], test_mean],
            [saved['population_certificate_raw'], saved['audit_only_test_posterior_risk']],
            atol=2e-12, rtol=2e-12)
        rows.append(dict(dataset=saved['dataset'], model=saved['architecture'],
                         k=int(saved['k']), **terms, test_risk=test_mean))
    return pd.DataFrame(rows)
