#!/usr/bin/env python3
"""Reproduce DN's bounded historical trade comparison; Python standard library only.

Usage: python recalculate.py path/to/trade_observations.json
With the public filenames, omit the argument when both downloads share a folder.
This script reads the eight supplied observations. It does not fetch data.
"""
import json
import sys
from decimal import Decimal, localcontext
from pathlib import Path


def calculate(document):
    rows = document['observations']
    expected = {(y, p) for y in (2023, 2024) for p in ('World', 'China', 'Mexico', 'Vietnam')}
    observed = [(r['year'], r['partner']) for r in rows]
    if len(observed) != 8 or set(observed) != expected:
        raise ValueError('Supply exactly one observation for each of the eight declared year/partner pairs.')
    values = {}
    for r in rows:
        if (r['reporter_code'], r['flow'], r['classification'], r['product_code']) != ('USA', 'gross imports', 'HS 1988/92 (H0)', '847330'):
            raise ValueError('Reporter, flow, nomenclature or product differs from the declared case.')
        v = Decimal(r['trade_value_1000_usd'])
        if not v.is_finite() or v <= 0:
            raise ValueError('This case requires positive finite observed values.')
        values[r['year'], r['partner']] = v
    with localcontext() as context:
        context.prec = 38
        world = {y: values[y, 'World'] for y in (2023, 2024)}
        comparisons = []
        for partner in ('China', 'Mexico', 'Vietnam'):
            first, last = values[2023, partner], values[2024, partner]
            if first > world[2023] or last > world[2024]:
                raise ValueError('A partner value exceeds the corresponding World total.')
            s0, s1 = first / world[2023] * 100, last / world[2024] * 100
            comparisons.append({'partner': partner, 'value_2023_1000_usd': str(first), 'value_2024_1000_usd': str(last), 'change_1000_usd': str(last-first), 'value_growth_percent': str((last/first-1)*100), 'share_2023_percent': str(s0), 'share_2024_percent': str(s1), 'share_change_percentage_points': str(s1-s0)})
        return {'calculation_version': '1.0.0', 'world_growth_percent': str((world[2024]/world[2023]-1)*100), 'world_change_1000_usd': str(world[2024]-world[2023]), 'comparisons': comparisons}


if __name__ == '__main__':
    here = Path(__file__).resolve()
    source = Path(sys.argv[1]) if len(sys.argv) > 1 else here.with_name('trade_observations.json')
    if not source.is_file() and len(sys.argv) == 1:
        source = here.with_name(here.stem.removesuffix('-recalculate') + '-observations.json')
    print(json.dumps(calculate(json.loads(source.read_text())), indent=2))
