#!/usr/bin/env python3
"""Independently check the MyProfitFactor moving-average comparison.

Put this file beside ma-comparison-guide-evidence.json and
ma-comparison-guide-candles.csv, then run:

    python3 ma-comparison-guide-check.py

To verify the checkpoint and replay the complete retained history as well:

    python3 ma-comparison-guide-check.py --reference xrp-hull-evidence.json

Only Python's standard library is used. Decimal arithmetic uses 50 significant
digits; constructed teaching examples and HMA coefficients use exact fractions.
This checks measurements, not a trading strategy or a profitability claim.
"""
from __future__ import annotations

import argparse
import csv
from datetime import datetime, timezone
from decimal import Decimal, getcontext
from fractions import Fraction
from hashlib import sha256
import json
from pathlib import Path
import re
import sys


getcontext().prec = 50
D = Decimal
INTERVAL = 4 * 60 * 60
TOLERANCE = D('1e-12')
REFERENCE_SHA = 'c59c30c69e7a2423ae18ab761687343da1ba21eacf6238d78e7b0410ead2a2d6'
REFERENCE_PROTOCOL_SHA = 'f870d7ec0f89dba357357c967653ae2c1d0e8727f668b9a6175eb4cbb108fe14'
METHODS = ('sma16', 'ema16', 'wma16', 'hma16')


class VerificationError(ValueError):
    pass


def require(condition, message):
    if not condition:
        raise VerificationError(message)


def utc(timestamp):
    return datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')


def decimal(value):
    if isinstance(value, Fraction):
        return D(value.numerator) / D(value.denominator)
    return D(str(value))


def load(path):
    return json.loads(path.read_text(encoding='utf-8'), parse_float=D)


class Comparisons:
    def __init__(self):
        self.count = 0
        self.maximum = D(0)

    def check(self, expected, observed, description):
        self.count += 1
        if expected is None or observed is None:
            require(expected is None and observed is None, description + ': unavailable-value mismatch')
            return
        a, b = decimal(expected), decimal(observed)
        require(a.is_finite() and b.is_finite(), description + ': nonfinite value')
        error = abs(a - b)
        self.maximum = max(self.maximum, error)
        require(error <= TOLERANCE, description + ': error ' + str(error))


class MovingAverages:
    """Independent trailing-window implementation; no project imports."""
    def __init__(self, n=16, half=8, root=4, number=D):
        self.n, self.half, self.root, self.number = n, half, root, number
        self.previous_ts = None
        self.clear()

    def clear(self):
        self.closes = []
        self.intermediate = []
        self.ema = None

    def weighted(self, values, length):
        if len(values) < length:
            return None
        values = values[-length:]
        return sum((self.number(i) * x for i, x in enumerate(values, 1)), self.number(0)) / self.number(length * (length + 1) // 2)

    def push(self, value, timestamp=None):
        if timestamp is not None and self.previous_ts is not None and timestamp - self.previous_ts != INTERVAL:
            self.clear()
        self.previous_ts = timestamp
        try:
            x = self.number(str(value)) if value is not None else None
            valid = x is not None and (not isinstance(x, D) or x.is_finite())
        except (ValueError, ArithmeticError):
            valid = False
        if not valid:
            self.clear()
            return {k + str(self.n): None for k in ('sma', 'ema', 'wma', 'raw_hma', 'hma')}
        self.closes.append(x)
        self.closes = self.closes[-self.n:]
        sma = sum(self.closes, self.number(0)) / self.number(self.n) if len(self.closes) == self.n else None
        if self.ema is None:
            self.ema = sma
        else:
            alpha = self.number(2) / self.number(self.n + 1)
            self.ema = (self.number(1) - alpha) * self.ema + alpha * x
        wma = self.weighted(self.closes, self.n)
        half = self.weighted(self.closes, self.half)
        raw = 2 * half - wma if wma is not None and half is not None else None
        if raw is None:
            self.intermediate = []
        else:
            self.intermediate.append(raw)
            self.intermediate = self.intermediate[-self.root:]
        hma = self.weighted(self.intermediate, self.root)
        return {k + str(self.n): v for k, v in (('sma', sma), ('ema', self.ema), ('wma', wma), ('raw_hma', raw), ('hma', hma))}


def kernel():
    # Polynomial convolution, newest input at lag zero, independent of the engine.
    inner = [Fraction(2 * (8 - age), 36) if age < 8 else Fraction(0) for age in range(16)]
    inner = [x - Fraction(16 - age, 136) for age, x in enumerate(inner)]
    outer = [Fraction(4 - age, 10) for age in range(4)]
    result = [Fraction(0)] * 19
    for a, x in enumerate(inner):
        for b, y in enumerate(outer):
            result[a + b] += x * y
    return result


def verify_teaching(data):
    comparisons = Comparisons()
    teaching = data['teaching']
    weights = teaching['weights4']['rows']
    require(len(weights) == 4, 'four weight observations required')
    for i, row in enumerate(weights, 1):
        require(row['observation'] == i, 'weight observation order')
        for field, expected in (('sma_weight', Fraction(1, 4)), ('wma_weight', Fraction(i, 10))):
            require(Fraction(row[field + '_exact']) == expected, 'exact teaching weight')
            comparisons.check(expected, row[field], field)
    require(sum(Fraction(r['sma_weight_exact']) for r in weights) == 1, 'SMA weights sum')
    require(sum(Fraction(r['wma_weight_exact']) for r in weights) == 1, 'WMA weights sum')

    for key, n, half, root, prices in (('ramp4', 4, 2, 2, [10, 20, 30, 40, 50]),
                                      ('step16', 16, 8, 4, [100] * 32 + [110] * 24)):
        rows = teaching[key]['rows']
        require(len(rows) == len(prices), key + ' length')
        if key == 'ramp4':
            require(teaching[key]['prices'] == prices, 'ramp input list')
        engine = MovingAverages(n, half, root, Fraction)
        calculated = []
        for i, (row, price) in enumerate(zip(rows, prices)):
            require(row['index'] == i and row['observation'] == i + 1, key + ' observation order')
            comparisons.check(price, row['close'], key + ' close')
            expected = engine.push(price)
            calculated.append(expected)
            for field, value in expected.items():
                require((None if value is None else Fraction(row['exact'][field])) == value, key + ' exact ' + field)
                comparisons.check(value, row[field], key + ' ' + field)
        if key == 'ramp4':
            require([calculated[3][f + '4'] for f in ('sma', 'ema', 'wma', 'hma')] == [25, 25, 30, None], 'fourth ramp observation')
            require([calculated[4][f + '4'] for f in ('sma', 'ema', 'wma', 'hma')] == [35, 35, 40, 50], 'fifth ramp observation')
        else:
            peak_i = max((i for i, row in enumerate(calculated) if row['hma16'] is not None), key=lambda i: calculated[i]['hma16'])
            peak = teaching[key]['peak']
            require(peak_i == peak['index'] == 39 and peak['post_step_observation'] == 8 and peak['observation'] == 40, 'step peak observation')
            require(calculated[peak_i]['hma16'] == Fraction(45905, 408) == Fraction(peak['hma16_exact']), 'exact HMA step peak')
            require(Fraction(peak['overshoot_exact']) == Fraction(1025, 408), 'exact overshoot')
            comparisons.check(calculated[peak_i]['hma16'], peak['hma16'], 'step peak decimal')
            for row in calculated:
                for field in ('sma16', 'ema16', 'wma16'):
                    require(row[field] is None or 100 <= row[field] <= 110, 'convex teaching output')

    coefficients = kernel()
    stored = teaching['kernel16']
    require(len(stored['rows']) == 19, 'HMA coefficient count')
    for age, (expected, row) in enumerate(zip(coefficients, stored['rows'])):
        require(row['age'] == age and Fraction(row['weight_exact']) == expected, 'coefficient direction and exact value')
        comparisons.check(expected, row['weight'], 'coefficient decimal')
    sums = {
        'sum_exact': sum(coefficients),
        'positive_sum_exact': sum(x for x in coefficients if x > 0),
        'negative_sum_exact': sum(x for x in coefficients if x < 0),
        'mean_age_exact': sum(age * x for age, x in enumerate(coefficients)),
    }
    require(sums['sum_exact'] == 1 and sums['mean_age_exact'] == Fraction(2, 3), 'kernel sum and mean age')
    for field, value in sums.items():
        require(Fraction(stored[field]) == value, field)
    require(sum(x < 0 for x in coefficients) == 11, 'negative HMA coefficients')
    return comparisons, coefficients


def verify_edge_cases():
    first = {}
    engine = MovingAverages()
    for i in range(1, 25):
        row = engine.push(i, i * INTERVAL)
        for field in METHODS:
            if row[field] is not None and field not in first:
                first[field] = i
    require(first == {'sma16': 16, 'ema16': 16, 'wma16': 16, 'hma16': 19}, 'first-validity counts')
    for constant in (0, 7, -3):
        engine = MovingAverages()
        for i in range(25):
            row = engine.push(constant, i * INTERVAL)
            require(all(value is None or value == constant for value in row.values()), 'constant input preservation')
    for invalid in (None, 'NaN', 'Infinity'):
        engine = MovingAverages()
        for i in range(25):
            engine.push(100, i * INTERVAL)
        require(all(v is None for v in engine.push(invalid, 25 * INTERVAL).values()), 'invalid input must reset')
        for j in range(1, 20):
            row = engine.push(110, (25 + j) * INTERVAL)
            require((row['ema16'] is None) == (j < 16), 'EMA reseed after invalid input')
            require((row['hma16'] is None) == (j < 19), 'HMA full windows after invalid input')
    engine = MovingAverages()
    for i in range(25):
        engine.push(100, i * INTERVAL)
    for j in range(1, 20):
        row = engine.push(110, (25 + j) * INTERVAL)  # Missing the scheduled timestamp 25.
        require((row['sma16'] is None) == (j < 16), 'finite windows must reset at a gap')
        require((row['ema16'] is None) == (j < 16), 'recursive seed must reset at a gap')
        require((row['hma16'] is None) == (j < 19), 'nested HMA must reset at a gap')
    return first


def verify_record(row):
    ts, scale = row['ts'], row['timestamp_scale']
    require(isinstance(ts, int) and scale in (1000, 1000000), 'timestamp type/scale')
    require(row['source_open_raw'] == ts * scale, 'source opening timestamp')
    require(row['opening_utc'] == utc(ts) and row['available_utc'] == utc(ts + INTERVAL), 'opening versus final availability')
    o, h, l, c = (decimal(row[k]) for k in ('open', 'high', 'low', 'close'))
    require(all(v.is_finite() for v in (o, h, l, c)) and 0 < l <= min(o, c) <= max(o, c) <= h, 'actual OHLC bounds')
    month = datetime.fromtimestamp(ts, timezone.utc).strftime('%Y-%m')
    require(row['source_zip'] == 'XRPUSDT-4h-' + month + '.zip' and row['source_member'] == 'XRPUSDT-4h-' + month + '.csv', 'source archive/member date')
    require(isinstance(row['source_row'], int) and row['source_row'] >= 1, 'one-based source row')


def verify_compact(data, csv_path):
    require(data['schema'] == 'mpf-moving-average-comparison-guide-v1', 'evidence schema')
    p = data['protocol']
    require(p['period'] == 16 and p['hma_half'] == 8 and p['hma_root'] == 4 and p['interval_seconds'] == INTERVAL, 'declared periods/interval')
    require(p['instrument'] == 'Binance Spot XRPUSDT' and p['price_units'] == 'USDT per XRP', 'instrument/price units')
    require(p['ema']['alpha'] == '2/17', 'EMA coefficient')
    require(p['first_valid_close_counts'] == {'sma16': 16, 'ema16': 16, 'wma16': 16, 'hma16': 19}, 'declared first-validity counts')
    provenance = data['provenance']
    require(provenance['reference_sha256'] == REFERENCE_SHA and provenance['reference_protocol_sha256'] == REFERENCE_PROTOCOL_SHA, 'frozen reference pins')
    archives = provenance['archives']
    require(len(archives) == 79 and len({a['name'] for a in archives}) == 79 and sum(a['rows'] for a in archives) == 14434, 'archive metadata counts')
    for a in archives:
        require(re.fullmatch('[0-9a-f]{64}', a['sha256']) and re.fullmatch('[0-9a-f]{64}', a['checksum_sha256']), 'archive hash syntax')
        require(a['checksum_verified'] is True and a['crc_verified'] is True, 'archive verification disclosure')
        require(a['url'] == 'https://data.binance.vision/data/spot/monthly/klines/XRPUSDT/4h/' + a['name'], 'official source archive URL')
        require(a['checksum_url'] == a['url'] + '.CHECKSUM', 'source checksum URL')
    context, displayed = data['context'], data['bars']
    require(len(context) == 16 and len(displayed) == 42, 'context/display lengths')
    require(displayed[0]['ts'] == 1704067200 and displayed[-1]['ts'] == 1704657600, 'fixed first UTC week of 2024')
    require(datetime.fromtimestamp(displayed[0]['ts'], timezone.utc).weekday() == 0, 'calendar window starts Monday')
    require(p['display_window']['opening_start_utc'] == displayed[0]['opening_utc'] and p['display_window']['opening_end_exclusive_utc'] == displayed[-1]['available_utc'], 'calendar window declaration')
    initial = data['initial_state']
    previous = initial['previous_closes']
    require(len(previous) == 18 and previous[-1]['ts'] == initial['previous_ts'], 'initial finite-window support')
    require(initial['state_available_utc'] == utc(initial['previous_ts'] + INTERVAL) == context[0]['opening_utc'], 'checkpoint availability boundary')
    timestamps = [r['ts'] for r in previous + context + displayed]
    require(all(b - a == INTERVAL for a, b in zip(timestamps, timestamps[1:])), 'compact records must remain adjacent')
    engine = MovingAverages()
    for row in previous:
        engine.push(row['close'], row['ts'])
    engine.ema = decimal(initial['ema16_previous'])
    require(engine.ema.is_finite(), 'finite EMA checkpoint')
    comparisons = Comparisons()
    for row in context + displayed:
        verify_record(row)
        values = engine.push(row['close'], row['ts'])
        for field in METHODS:
            comparisons.check(values[field], row[field], 'continuation ' + field)
            comparisons.check(decimal(row['close']) - values[field], row['difference_' + field], 'continuation price distance ' + field)
    expected_fields = ['ts', 'opening_utc', 'available_utc', 'open', 'high', 'low', 'close', *METHODS,
                       *('difference_' + field for field in METHODS), 'source_zip', 'source_member',
                       'source_row', 'source_open_raw', 'source_close_raw', 'timestamp_scale']
    with csv_path.open(encoding='utf-8-sig', newline='') as handle:
        reader = csv.DictReader(handle)
        require(reader.fieldnames == expected_fields, 'complete ordered CSV header')
        table = list(reader)
    require(len(table) == 42, 'CSV row count')
    for csv_row, row in zip(table, displayed):
        for key, value in csv_row.items():
            require(key in row, 'unknown CSV field ' + key)
            if key in METHODS or key.startswith('difference_'):
                comparisons.check(row[key], value, 'CSV ' + key)
            else:
                require(value == str(row[key]), 'CSV raw/source field ' + key)
    return comparisons


def verify_reference(data, path, coefficients):
    require(sha256(path.read_bytes()).hexdigest() == REFERENCE_SHA, 'original XRP evidence SHA256')
    reference = load(path)
    require(reference['protocol_sha256'] == REFERENCE_PROTOCOL_SHA, 'original protocol pin')
    bars = reference['bars']
    require(len(bars) == data['provenance']['reference_bars'] == 14434, 'full reference row count')
    original_sources = {r['file']: r['sha256'] for r in reference['data_quality']['sources']}
    require(original_sources == {r['name']: r['sha256'] for r in data['provenance']['archives']}, 'all archive pins match original reference')
    target = {r['ts']: r for r in data['context'] + data['bars']}
    previous = {r['ts']: r['close'] for r in data['initial_state']['previous_closes']}
    engine = MovingAverages()
    history = []
    last = None
    gaps = []
    comparisons = Comparisons()
    fir_checks = 0
    fir_maximum = D(0)
    target_count = 0
    carry_seen = False
    archive_rows = {}
    scale_counts = {}
    noncanonical_closes = 0
    coeff = [decimal(x) for x in coefficients]
    for row in bars:
        ts, close = row['ts'], decimal(row['close'])
        archive = 'XRPUSDT-4h-' + datetime.fromtimestamp(ts, timezone.utc).strftime('%Y-%m') + '.zip'
        archive_rows[archive] = archive_rows.get(archive, 0) + 1
        scale = row['timestamp_scale']
        require(scale in (1000, 1000000), 'full-history timestamp scale')
        scale_counts[str(scale)] = scale_counts.get(str(scale), 0) + 1
        if row['source_close_raw'] != (ts + INTERVAL) * scale - 1:
            noncanonical_closes += 1
        if last is not None:
            require(ts > last, 'reference chronological order')
            if ts - last != INTERVAL:
                require((ts - last) % INTERVAL == 0, 'reference schedule alignment')
                gaps.append({'left_observed_utc': utc(last), 'right_observed_utc': utc(ts), 'missing': (ts - last) // INTERVAL - 1})
                history = []
        values = engine.push(close, ts)
        history.append(close)
        history = history[-19:]
        if values['hma16'] is not None:
            require(len(history) == 19, 'HMA finite support')
            fir = sum((weight * price for weight, price in zip(coeff, reversed(history))), D(0))
            error = abs(fir - values['hma16'])
            fir_maximum = max(fir_maximum, error)
            require(error < D('1e-45'), 'nested/FIR high-precision identity')
            fir_checks += 1
        if ts in previous:
            require(close == decimal(previous[ts]), 'initial retained close matches source')
            previous.pop(ts)
        if ts == data['initial_state']['previous_ts']:
            comparisons.check(values['ema16'], data['initial_state']['ema16_previous'], 'full-history EMA checkpoint')
            carry_seen = True
        if ts in target:
            saved = target[ts]
            require(saved['source_zip'] == archive and saved['source_row'] == archive_rows[archive], 'one-based raw source row in monthly archive')
            for key in ('open', 'high', 'low', 'close', 'volume'):
                require(decimal(row[key]) == decimal(saved[key]), 'source OHLCV ' + key)
            for key in ('source_close_raw', 'timestamp_scale'):
                require(row[key] == saved[key], 'source timestamp field ' + key)
            for field in METHODS:
                comparisons.check(values[field], saved[field], 'full-history ' + field)
                comparisons.check(close - values[field], saved['difference_' + field], 'full-history distance ' + field)
            target_count += 1
        last = ts
    require(not previous and carry_seen and target_count == 58, 'all checkpoints/context/display found in reference')
    require(gaps == data['provenance']['missing_intervals'], 'disclosed missing intervals')
    require(archive_rows == {r['name']: r['rows'] for r in data['provenance']['archives']}, 'all monthly source row counts')
    require(scale_counts == data['provenance']['timestamp_scale_row_counts'], 'full-history timestamp-unit counts')
    require(noncanonical_closes == 11, 'preserved original close-timestamp anomalies')
    require(utc(bars[0]['ts']) == data['provenance']['history_start_utc'] and utc(bars[-1]['ts']) == data['provenance']['history_last_open_utc'], 'retained-history boundaries')
    require(fir_checks == 14380, 'valid HMA full-history count')
    return {'full_warmup_bars': len(bars), 'full_series_replayed': list(METHODS), 'replayed_context_and_display': target_count,
            'reference_hash': 'matched', 'full_reference_max_abs_error': str(comparisons.maximum),
            'reference_comparisons': comparisons.count, 'gap_resets': len(gaps), 'fir_comparisons': fir_checks,
            'nested_fir_max_abs_error': str(fir_maximum), 'monthly_source_row_counts_checked': len(archive_rows),
            'timestamp_unit_counts': scale_counts, 'preserved_noncanonical_close_timestamps': noncanonical_closes}


def main():
    base = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--evidence', type=Path, default=base / 'ma-comparison-guide-evidence.json')
    parser.add_argument('--csv', type=Path, default=base / 'ma-comparison-guide-candles.csv')
    parser.add_argument('--reference', type=Path, help='Optional unchanged original xrp-hull-evidence.json for full-history replay')
    args = parser.parse_args()
    try:
        data = load(args.evidence)
        teaching, coefficients = verify_teaching(data)
        first = verify_edge_cases()
        compact = verify_compact(data, args.csv)
        result = {'status': 'passed', 'method': 'Independent Decimal50 replay and exact Fraction teaching arithmetic; no project imports.',
                  'display_bars': 42, 'context_bars': 16, 'initial_closes': 18, 'continuation_records': 58,
                  'csv_rows_checked': 42, 'continuation_and_csv_comparisons': compact.count,
                  'continuation_and_csv_max_abs_error': str(compact.maximum), 'teaching_comparisons': teaching.count,
                  'teaching_max_abs_error': str(teaching.maximum), 'first_valid_close_counts': first,
                  'step_peak_exact': '45905/408', 'step_peak_index': 39, 'step_peak_post_change_observation': 8,
                  'kernel_coefficients': 19, 'negative_coefficients': 11, 'kernel_sum_exact': '1',
                  'constant_gap_invalid_cases': 'passed', 'archive_metadata_pins': 79,
                  'absolute_numeric_tolerance': str(TOLERANCE), 'reference_hash': 'not supplied',
                  'full_warmup_bars': 0}
        if args.reference:
            result.update(verify_reference(data, args.reference, coefficients))
        else:
            result['limitation'] = 'Compact continuation accepts the disclosed EMA checkpoint; add --reference to verify it from the beginning of retained history.'
        print(json.dumps(result, ensure_ascii=False))
    except (VerificationError, KeyError, OSError, ValueError, ArithmeticError) as error:
        print(json.dumps({'status': 'failed', 'error': str(error)}, ensure_ascii=False), file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
