#!/usr/bin/env python3
"""Offline Decimal50 checker for the MyProfitFactor Vortex/DMI/ADX guide.

Save this script, vortex-adx-guide-evidence.json and
vortex-adx-guide-candles.csv in the same directory, then run:
    python3 vortex-adx-guide-check.py

Optional full retained-history verification:
    python3 vortex-adx-guide-check.py --reference /path/eurusd-vortex-evidence.json

External locations work with --evidence PATH and --csv PATH. Standard library
only; no project module or network request. Small mode checks continuation
from the disclosed recursive state. Full-reference mode additionally verifies
that state's lineage by replaying the pinned original 10,596 OHLC records.
The source archive hashes are provenance metadata; this checker does not
claim to verify original ZIP bytes unless those files are independently read.
"""
from decimal import Decimal, getcontext
from datetime import datetime, timezone
from hashlib import sha256
from pathlib import Path
import argparse
import csv
import json

getcontext().prec=50
D=Decimal
SCALE=D(1000000)
FIELDS=('tr','vm_plus','vm_minus','dm_plus','dm_minus','vi_plus','vi_minus','di_plus','di_minus','dx','adx')
SOURCE_PIN='4e9587b22a95a0a879e3dfe06b09270a1d77b0fef28cd360e1f8d3a9786d15e7'
DEFAULT_ROOT=Path(__file__).resolve().parent
TOLERANCE=D('1e-10')


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


def hlc(bar):
    values=tuple(int(bar['source_'+k+'_int'])for k in ('high','low','close'))
    assert values[1]<=values[2]<=values[0],('invalid HLC',bar)
    return values


def replay(bars,n=14,state=None):
    previous=hlc(state['previous_bar'])if state else None
    window=[tuple(x)for x in state['window']]if state else []
    averages=tuple(D(str(v))for v in state['rma'])if state else None
    seed=[D(str(v))for v in state['dx_seed']]if state else []
    adx=D(str(state['adx']))if state and state['adx']is not None else None
    rows,states=[],[]
    if state:
        assert len(window)==n and len(averages)==3 and len(seed)==n
        assert all(len(x)==5 and all(isinstance(v,int)and v>=0 for v in x)for x in window)
        assert all(v>=0 for v in averages)
    for bar in bars:
        h,l,c=hlc(bar)
        row=dict.fromkeys(FIELDS)
        if previous is not None:
            ph,pl,pc=previous
            up,down=h-ph,pl-l
            raw=(max(h-l,abs(h-pc),abs(l-pc)),abs(h-pl),abs(l-ph),
                 max(up,0)if up>down else 0,max(down,0)if down>up else 0)
            window.append(raw)
            window=window[-n:]
            for name,value in zip(FIELDS[:5],raw):
                row[name]=D(value)/SCALE
            if len(window)==n:
                sums=tuple(sum(x[k]for x in window)for k in range(5))
                if sums[0]:
                    row['vi_plus']=D(sums[1])/D(sums[0])
                    row['vi_minus']=D(sums[2])/D(sums[0])
                current=tuple(D(raw[k])for k in (0,3,4))
                if averages is None:
                    averages=tuple(D(sums[k])/D(n)for k in (0,3,4))
                else:
                    averages=tuple(a+(x-a)/D(n)for a,x in zip(averages,current))
                p=100*averages[1]/averages[0]if averages[0]else D(0)
                m=100*averages[2]/averages[0]if averages[0]else D(0)
                dx=100*abs(p-m)/(p+m)if p+m else D(0)
                if adx is None:
                    seed.append(dx)
                    if len(seed)==n:
                        adx=sum(seed)/D(n)
                else:
                    adx+=(dx-adx)/D(n)
                row.update(di_plus=p,di_minus=m,dx=dx,adx=adx)
        previous=h,l,c
        rows.append(row)
        states.append({'previous_bar':dict(zip(('source_high_int','source_low_int','source_close_int'),previous)),
                       'window':window.copy(),'rma':averages,'dx_seed':seed.copy(),'adx':adx})
    return rows,states


def close_enough(expected,actual,tag,maxima,tolerance=TOLERANCE):
    if expected is None or actual is None:
        assert expected is None and actual is None,(tag,expected,actual)
        return
    error=abs(D(str(expected))-D(str(actual)))
    maxima[tag.split(':')[0]]=max(maxima.get(tag.split(':')[0],D(0)),error)
    assert error<=tolerance,(tag,str(expected),actual,str(error))


def compare_rows(expected,actual,tag,maxima):
    assert len(expected)==len(actual),(tag,'row count')
    for i,(a,b)in enumerate(zip(expected,actual)):
        for name in FIELDS:
            close_enough(a[name],b[name],tag+':'+str(i)+':'+name,maxima)


def constructed(values,width=1000000):
    return [{'source_high_int':c+width,'source_low_int':c-width,'source_close_int':c}for c in values]


def test_arithmetic(evidence,maxima):
    for path in evidence['teaching']['paths']:
        expected,_=replay(path['rows'],3)
        compare_rows(expected,path['rows'],'teaching',maxima)
    for case in evidence['teaching']['cases']:
        previous={'source_'+k+'_int':int(D(str(case['previous_'+k]))*SCALE)for k in ('high','low','close')}
        current={'source_'+k+'_int':int(D(str(case[k]))*SCALE)for k in ('high','low','close')}
        expected,_=replay([previous,current],1)
        compare_rows([expected[-1]],[case],'case',maxima)
    rise=constructed([100000000+i*1000000 for i in range(40)])
    rows,_=replay(rise)
    starts={k:next(i+1 for i,r in enumerate(rows)if r[k]is not None)for k in ('vi_plus','di_plus','dx','adx')}
    assert starts=={'vi_plus':15,'di_plus':15,'dx':15,'adx':28}
    for r in rows[14:]:
        assert r['vi_plus']==D('1.5')and r['vi_minus']==D('0.5')
    flat,_=replay(constructed([100000000]*40,width=0))
    assert all(r['vi_plus']is None and r['vi_minus']is None for r in flat)
    assert all(r['di_plus']==r['di_minus']==r['dx']==0 for r in flat[14:])
    assert all(r['adx']==0 for r in flat[27:])
    still,_=replay(constructed([100000000]*40))
    assert all(r['vi_plus']==r['vi_minus']==1 and r['dx']==0 for r in still[14:])
    varied=constructed([100000000+(i%7-3)*150000+((i//7)%5)*70000 for i in range(80)])
    original,_=replay(varied)
    affine=[{'source_'+k+'_int':7*b['source_'+k+'_int']+123456789 for k in ('high','low','close')}for b in varied]
    mirror=[{'source_high_int':300000000-b['source_low_int'],
             'source_low_int':300000000-b['source_high_int'],
             'source_close_int':300000000-b['source_close_int']}for b in varied]
    scaled,_=replay(affine)
    reflected,_=replay(mirror)
    for a,b,c in zip(original,scaled,reflected):
        for k in ('vi_plus','vi_minus','di_plus','di_minus','dx','adx'):
            close_enough(a[k],b[k],'affine:'+k,maxima,D('1e-45'))
        for k,j in (('vi_plus','vi_minus'),('vi_minus','vi_plus'),('di_plus','di_minus'),('di_minus','di_plus'),('dx','dx'),('adx','adx')):
            close_enough(a[k],c[j],'reflection:'+k,maxima,D('1e-45'))
    prefix,_=replay(rise[:20])
    assert prefix==rows[:20]
    return starts


def iso(ts):
    return datetime.fromtimestamp(ts,timezone.utc).isoformat(timespec='seconds').replace('+00:00','Z')


def main():
    parser=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--evidence',type=Path,default=DEFAULT_ROOT/'vortex-adx-guide-evidence.json')
    parser.add_argument('--csv',type=Path,default=DEFAULT_ROOT/'vortex-adx-guide-candles.csv')
    parser.add_argument('--reference',type=Path,help='Optional pinned original EURUSD study evidence JSON')
    args=parser.parse_args()
    evidence=load(args.evidence)
    assert evidence['protocol']['original_sha256']==SOURCE_PIN
    assert evidence['protocol']['n']==evidence['protocol']['di_length']==evidence['protocol']['adx_length']==14
    published=evidence['context']+evidence['bars']
    assert len(evidence['context'])==14 and len(evidence['bars'])==26
    maxima={}
    continued,_=replay(published,state=evidence['initial_state'])
    compare_rows(continued,published,'continuation',maxima)
    assert all(b['ts']>a['ts']for a,b in zip(published,published[1:]))
    for row in published:
        assert row['ts']%14400==0 and row['anchor_utc']==iso(row['ts'])
        assert row['available_utc']==iso(row['ts']+14400)
        assert row['first_minute_utc']==iso(row['first_ts'])and row['last_minute_utc']==iso(row['last_ts'])
        assert row['ts']<=row['first_ts']<=row['last_ts']<row['ts']+14400
        assert 0<row['n']<=240
        for k in ('open','high','low','close'):
            assert D(str(row[k]))*SCALE==row['source_'+k+'_int']
    assert sum(r['n']for r in evidence['bars'])==5854
    assert sum(r['n']==240 for r in evidence['bars'])==16
    assert all(1704067200<=r['ts']<1704672000 for r in evidence['bars'])
    with args.csv.open(encoding='utf-8',newline='')as f:
        reader=csv.DictReader(f)
        assert reader.fieldnames==['anchor_utc','available_utc','first_minute_utc','last_minute_utc','n','open','high','low','close','tr','vi_plus','vi_minus','di_plus','di_minus','dx','adx']
        csv_rows=list(reader)
    assert len(csv_rows)==26
    for row,truth in zip(csv_rows,evidence['bars']):
        for key,value in row.items():
            if key.endswith('_utc'):
                assert value==truth[key]
            else:
                close_enough(truth[key],value,'csv:'+key,maxima)
    starts=test_arithmetic(evidence,maxima)
    full_bars=0
    if args.reference:
        assert sha256(args.reference.read_bytes()).hexdigest()==SOURCE_PIN,'Original reference SHA256 mismatch'
        original=load(args.reference)
        assert original['protocol_sha256']==evidence['protocol']['original_protocol_sha256']
        history=original['bars']
        assert len(history)==10596
        full,states=replay(history)
        by_ts={b['ts']:i for i,b in enumerate(history)}
        expected=[full[by_ts[b['ts']]]for b in published]
        compare_rows(expected,published,'full_reference',maxima)
        offset=evidence['quality']['initial_history_bars']
        assert by_ts[published[0]['ts']]==offset
        state=states[offset-1]
        supplied=evidence['initial_state']
        assert state['previous_bar']==supplied['previous_bar']
        assert [list(x)for x in state['window']]==supplied['window']
        for a,b in zip(state['rma'],supplied['rma']):
            close_enough(a,b,'seed_rma:integer_price_units',maxima,D('1e-9'))
        assert len(state['dx_seed'])==len(supplied['dx_seed'])==14
        for a,b in zip(state['dx_seed'],supplied['dx_seed']):
            close_enough(a,b,'seed_dx:points',maxima)
        close_enough(state['adx'],supplied['adx'],'seed_adx:points',maxima)
        for row in published:
            source=history[by_ts[row['ts']]]
            for k in ('source_open_int','source_high_int','source_low_int','source_close_int','n','first_ts','last_ts'):
                assert row[k]==source[k],(row['ts'],k)
        full_bars=len(history)
    result={'status':'passed','arithmetic':'Decimal50, independent of project calculation modules',
            'context_records':14,'display_records':26,'csv_rows':len(csv_rows),
            'first_valid_bar_counts':starts,'full_history_replayed':full_bars,
            'initial_recursive_state':'verified from pinned original history'if args.reference else'disclosed input state; its earlier lineage requires --reference',
            'zero_denominators':'VI unavailable for zero rolling TR; DI 0 for zero smoothed TR; DX 0 for zero DI sum',
            'synthetic_and_invariance_cases':'passed',
            'maximum_absolute_errors':{k:str(v)for k,v in maxima.items()},
            'source_zip_bytes_checked':False}
    print(json.dumps(result,ensure_ascii=False,indent=2))


if __name__=='__main__':
    main()
