"""Retain the existing method A implementation comparison on its exact grid.

This supplements verify.py's maximum with the per-date observations and mean.
It does not change either implementation or establish financial-model soundness.
"""
import csv
from datetime import date
import hashlib
import json
import math
from pathlib import Path


def summarize(rows):
    if not rows:
        raise ValueError('comparison grid is empty')
    dates = [date.fromisoformat(row['date']) for row in rows]
    if dates != sorted(set(dates)):
        raise ValueError('grid dates must be unique and increasing')
    differences = []
    for row in rows:
        values = [row['quantlib_df'], row['hagan_west_loglinear_df']]
        if any(not math.isfinite(value) or value <= 0 for value in values):
            raise ValueError('discount factors must be finite and positive')
        differences.append(abs(values[0] - values[1]))
    largest = max(differences)
    return {'count': len(rows), 'first_date': dates[0].isoformat(),
            'last_date': dates[-1].isoformat(),
            'maximum_absolute_df_difference': largest,
            'mean_absolute_df_difference': math.fsum(differences) / len(differences),
            'maximum_dates': [row['date'] for row, value in zip(rows, differences) if value == largest]}


def main():
    import QuantLib as ql
    import bootstrap as bs
    import hagan_west as hw

    ql.Settings.instance().evaluationDate = bs.AS_OF
    quotes, on_rate = bs.load_inputs()
    base = bs.CurveSet(quotes, on_rate)
    comparison = hw.bootstrap(base.deposits, base.swaps, 'loglinear')
    days = bs.business_days(bs.AS_OF, max(base.pillars))
    rows = [{'date': bs.pydate(day).isoformat(),
             'quantlib_df': base.df('A', day),
             'hagan_west_loglinear_df': comparison.discount(bs.T(day))}
            for day in days]
    summary = summarize(rows)
    for row in rows:
        row['absolute_df_difference'] = abs(row['quantlib_df'] - row['hagan_west_loglinear_df'])

    original = json.loads((bs.OUT / 'verify.json').read_text())
    name = 'Method A: QuantLib against hagan_west.py log-linear bootstrap, max abs discount-factor difference (daily)'
    matches = [item for item in original['checks'] if item['check'] == name]
    if len(matches) != 1 or matches[0]['unit'] != 'abs':
        raise ValueError('original method A comparison is missing or ambiguous')
    recorded = matches[0]['measured']
    if not math.isclose(summary['maximum_absolute_df_difference'], recorded, rel_tol=1e-12, abs_tol=1e-20):
        raise ValueError('reproduced maximum differs from the historical comparison')
    inputs = ['out/quotes.csv', 'out/sofr_fixing.json', 'out/verify.json',
              'bootstrap.py', 'hagan_west.py', 'verify.py', 'summarize_implementations.py']
    record = {'as_of': bs.pydate(bs.AS_OF).isoformat(),
              'method': 'A: log-linear discount factors',
              'implementations': ['QuantLib', 'hagan_west.py loglinear bootstrap'],
              'unit': 'absolute dimensionless discount factor',
              'grid': 'AS_OF through the last instrument pillar, inclusive; successive SOFR-calendar business days, exactly as verify.py',
              'summary': summary, 'original_maximum': recorded,
              'input_sha256': {name: hashlib.sha256((bs.HERE / name).read_bytes()).hexdigest() for name in inputs},
              'limits': 'Shared quotes, schedules and financial conventions. Agreement between implementations does not establish financial-model correctness. This supplement covers method A only.'}
    with (bs.OUT / 'implementation-comparison.csv').open('w', newline='') as stream:
        writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    record['series_sha256'] = hashlib.sha256((bs.OUT / 'implementation-comparison.csv').read_bytes()).hexdigest()
    (bs.OUT / 'implementation-comparison.json').write_text(json.dumps(record, indent=2) + '\n')
    (bs.OUT / 'implementation-comparison.md').write_text(f'''# Method A implementation comparison

As of {record['as_of']}. Both implementations use the same quote and fixing snapshot, instruments and schedules. The comparison retains the original `verify.py` grid: {summary['count']} observations from {summary['first_date']} through {summary['last_date']}, inclusive, advancing by SOFR-calendar business days.

| Comparison | Maximum absolute DF difference (dimensionless) | Mean absolute DF difference (dimensionless) |
|---|---:|---:|
| QuantLib method A vs hagan_west.py loglinear bootstrap | {summary['maximum_absolute_df_difference']:.12e} | {summary['mean_absolute_df_difference']:.12e} |

Source: `summarize_implementations.py`, using `out/quotes.csv` and `out/sofr_fixing.json` from the 2026-09-18 public-data snapshot. Exact per-date values are in `out/implementation-comparison.csv`; definitions and input hashes are in `out/implementation-comparison.json`. The maximum reproduces the original `out/verify.json` method A comparison. Runtime package identities are recorded separately in `out/environment/implementation-summary.json` when run through `run.sh`.

{record['limits']} No institution-specific evidence is supplied.
''')
    print(json.dumps(summary))


if __name__ == '__main__':
    main()
