"""Proof of Foresight: build one round's commitment (protocol 1.0, see PROTOCOL.md).
  python foresight/commit.py ROUND INPUT_XLSX INPUT_URL OUT_DIR   (ROUND = 'YYYY-MM', the month the round is made in)
Writes OUT_DIR/commitment.json (canonical JSON: sorted keys, no spaces, UTF-8), commitment.sha256 and inputs.csv.gz.
Timestamps, the Rekor entry and the archive snapshot are added by the workflow after this file exists; they cover the
exact bytes of commitment.json and cannot be added before it."""
import csv, gzip, hashlib, json, math, os, sys, time, urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import model as M
from rosstat import parse, SERIES

ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
sha = lambda b: hashlib.sha256(b).hexdigest()
canon = lambda o: json.dumps(o, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
NAMES = {'rs-rent1': ('Аренда однокомнатной квартиры у частных лиц, месяц', 'Rent of a one-room flat from a private owner, per month'),
         'rs-rent2': ('Аренда двухкомнатной квартиры у частных лиц, месяц', 'Rent of a two-room flat from a private owner, per month'),
         'rs-transit': ('Проезд в городском муниципальном автобусе, поездка', 'Municipal city bus, one trip'),
         'rs-kinder': ('Присмотр и уход за ребенком в государственном детском саду, месяц', 'Care of a child in a state kindergarten, per month'),
         'rs-water': ('Водоснабжение холодное, м3', 'Cold water supply, per m3'), 'rs-heat': ('Отопление, Гкал', 'Heating, per Gcal'),
         'rs-power': ('Электроэнергия в квартирах без электроплит, 100 кВт·ч', 'Electricity in flats without electric stoves, per 100 kWh'),
         'rs-school-private': ('Обучение в негосударственной общеобразовательной школе, месяц', 'Private general school, per month'),
         'rs-uni-private': ('Обучение в негосударственном вузе, семестр', 'Private university, per semester'),
         'rs-uni-public': ('Обучение в государственном вузе, семестр', 'State university (fee-paying place), per semester'),
         'rs-doctor': ('Первичный прием у врача-специалиста', 'First visit to a specialist doctor'), 'rs-dentist': ('Первичный прием у стоматолога', 'First visit to a dentist'),
         'rs-filling': ('Пломба из композитного материала', 'Composite filling'), 'rs-bloodtest': ('Общий анализ крови', 'Complete blood count')}

def probe(url):
    """status of a target file at commitment time; it is expected not to exist yet (404). Rosstat needs the Russian CA
    bundle that pipeline/net.py carries; without it the probe records the error instead of a status."""
    when = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
    try:
        sys.path.insert(0, os.path.join(ROOT, 'pipeline')); from net import get
        st, ct, b = get(url, headers={'Referer': 'https://rosstat.gov.ru/', 'Range': 'bytes=0-0'}, timeout=60, tries=1)
    except Exception as e:
        st = getattr(e, 'code', None) or 'error: ' + type(e).__name__
    return {'url': url, 'status': st, 'checked': when}

def build(rnd, H, periods, filemeta, out, now=None, code_commit=None):
    last = periods[-1]
    if not rnd.startswith('sim') and last != M.add(rnd, -1):
        raise SystemExit(f'no round {rnd}: the latest published month is {last}, protocol 1.0 needs {M.add(rnd, -1)} (the round is skipped and logged)')
    targets = [M.add(last, h) for h in (1, 2)]
    series = sorted({s for (p, r, s) in H})
    here = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'regions.json')
    regions = {r['id']: r for r in json.load(open(here if os.path.exists(here) else os.path.join(ROOT, 'media', 'data', 'regions.json'), encoding='utf-8'))}
    bt = M.backtest(H, series, last)
    fc, iv, sv = [], {}, {}
    for s in series:
        prof = M.profile(H, s, last)
        sv[s] = {'code': next(k for k, v in SERIES.items() if v == s), 'ru': NAMES[s][0], 'en': NAMES[s][1], 'unit': 'RUB', 'class': prof['class'],
                 'zero_share': prof['zero_share'], 'step_months': prof['step_months'], 'common_drift': round(prof['common_drift'], 6)}
        pooled = {h: [e for ss in series if M.profile(H, ss, last)['class'] == prof['class'] for (_, _, _, e, _) in bt[ss][h]] for h in (1, 2)}
        iv[s] = {}
        for h in (1, 2):
            t = targets[h - 1]
            qs, n, src = M.error_quantiles(bt, s, h, prof['sticky'], any(M.add(last, k)[5:] == p[5:] for k in range(1, h + 1) for p in prof['step_months']), pooled[h])
            iv[s][str(h)] = {'log_error_quantiles': [round(q, 6) for q in qs], 'n_errors': n, 'source': src}
            for r in sorted({rr for (p, rr, ss) in H if ss == s and p == last}):
                f = M.points(H, s, r, last, h, prof)
                if not f: continue
                fc.append({'u': r, 's': s, 't': t, 'h': h, 'last': H[(last, r, s)], 'b0': round(f['b0'], 2), 'b1': round(f['b1'], 2),
                           'm1': [round(f['m1'] * math.exp(q), 2) for q in qs]})
    src_files = ['model.py', 'rosstat.py', 'commit.py', 'score.py']
    proto = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'PROTOCOL.md'), 'rb').read()
    base = 'https://rosstat.gov.ru/storage/mediabank/'
    c = {
        'type': 'wir.foresight.commitment/v1', 'round': rnd, 'created': now or time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
        'issuer': {'name': 'Where in Russia', 'url': 'https://whereinrussia.com', 'jwks': 'https://whereinrussia.com/.well-known/jwks.json'},
        'protocol': {'version': '1.0', 'url': 'https://whereinrussia.com/foresight/PROTOCOL.md', 'sha256': sha(proto)},
        'source': {'publisher': 'Rosstat (Federal State Statistics Service)', 'dataset': 'Средние потребительские цены на отдельные виды товаров и услуг по субъектам Российской Федерации',
                   'page': 'https://rosstat.gov.ru/statistics/price', 'measured': 'end of each month (по состоянию на конец месяца)'},
        'information_set': {'last_period': last, 'periods': periods, 'file': filemeta, 'values': len(H),
                            'parsed_inputs': 'inputs.csv.gz'},
        'availability_probe': [probe(f'{base}sred_potreb_cen_{t[5:]}-{t[:4]}.xlsx') for t in targets],
        'targets': [{'period': t, 'horizon': h, 'resolves_with': f'sred_potreb_cen_{t[5:]}-{t[:4]}.xlsx', 'primary': 'first release', 'secondary': 'latest release at scoring time'} for h, t in ((1, targets[0]), (2, targets[1]))],
        'code': {'model_version': M.MODEL_VERSION, 'repository_commit': code_commit or os.environ.get('GITHUB_SHA', ''),
                 'sha256': {f: sha(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), f), 'rb').read()) for f in src_files},
                 'public_copy': 'https://whereinrussia.com/foresight/code/'},
        'parameters': {'quantiles': M.QUANTILES, 'sticky_share': M.STICKY_SHARE, 'continuous_share': M.CONTINUOUS_SHARE, 'step_share': M.STEP_SHARE,
                       'drift_window': M.DRIFT_WINDOW, 'min_errors': M.MIN_ERRORS},
        'models': {'b0': 'naive: last published value', 'b1': "drift: last value x exp(h x the region's mean monthly log change over the last 6 months)",
                   'm1': 'continuous series: last value x exp(h x cross-region median of 6-month mean change); other series: last value; '
                         'quantiles: point x exp(empirical quantiles of pseudo-out-of-sample log errors), administered series conditioned on whether a step month of the series falls in the window'},
        'series': sv, 'intervals': iv,
        'units': {r: {'en': regions[r]['en'], 'ru': regions[r]['ru'],
                      'international_status': 'disputed2014' if 'k' in regions[r]['flags'] else 'disputed2022' if 'z' in regions[r]['flags'] else 'recognised'}
                  for r in sorted({f['u'] for f in fc})},
        'units_not_published_by_source': sorted(set(regions) - {f['u'] for f in fc}),
        'forecasts': fc,
        'notes': ['Integrity (these bytes existed at the timestamped time and were issued by this key) is separate from accuracy (how close they were); both are reported, never merged.',
                  'Forecasts of one series across regions, and the two horizons, are statistically dependent; inference uses a cluster bootstrap by region (see PROTOCOL.md).',
                  'Status labels follow the platform\'s status layer (UN General Assembly resolutions 68/262 and ES-11/4); the label is a fact about international recognition, not a position.'],
    }
    os.makedirs(out, exist_ok=True)
    body = canon(c)
    open(os.path.join(out, 'commitment.json'), 'wb').write(body)
    open(os.path.join(out, 'commitment.sha256'), 'w').write(sha(body) + '  commitment.json\n')
    with gzip.open(os.path.join(out, 'inputs.csv.gz'), 'wt', newline='', encoding='utf-8') as f:
        w = csv.writer(f); w.writerow(['period', 'region', 'series', 'value']); w.writerows(sorted((p, r, s, f'{v:.2f}') for (p, r, s), v in H.items()))
    return c, sha(body)

if __name__ == '__main__':
    rnd, xlsx, url, out = sys.argv[1:5]
    b = open(xlsx, 'rb').read(); H, periods = parse(b)
    c, h = build(rnd, H, periods, {'url': url, 'sha256': sha(b), 'bytes': len(b)}, out)
    print(json.dumps({'round': rnd, 'sha256': h, 'forecasts': len(c['forecasts']), 'last_period': c['information_set']['last_period'],
                      'probe': c['availability_probe'], 'units': len(c['units'])}, ensure_ascii=False))
