#!/usr/bin/env python3
"""Check downloaded TSI-guide inputs with independent Decimal/Fraction arithmetic.

Keep this script beside tsi-crossings-guide-evidence.json and, optionally, its CSV.
For a full historical replay add --reference eth-tsi-evidence.json.
No network access or third-party packages are required.
"""
from pathlib import Path
from decimal import Decimal, localcontext
from fractions import Fraction
from hashlib import sha256
import argparse
import csv
import json

PERIOD=14400
FIELDS=('p25','a25','p13','a13','tsi','signal7','difference')
EVENTS=('zero_up','zero_down','signal_up','signal_down')
D=lambda x:Decimal(str(x))

def near(actual,expected,label):
    assert(actual is None)==(expected is None),label
    if actual is not None:assert abs(actual-D(expected))<D('0.00000001'),(label,str(actual),expected)

def event_flags(before,now):
    result={}
    for key in('zero','signal'):
        field='tsi'if key=='zero'else'difference'
        left=before.get(field)if before else None;right=now.get(field)
        valid=left is not None and right is not None
        result[key+'_up']=bool(valid and left<=0 and right>0)
        result[key+'_down']=bool(valid and left>=0 and right<0)
    return result

def continuation(evidence):
    previous={k:(D(v)if k!='ts'else v)for k,v in evidence['initial_state'].items()}
    checked=[]
    for b in evidence['context']+evidence['bars']:
        assert b['ts']==previous['ts']+PERIOD
        m=D(b['close'])-previous['close']
        p25=(D(12)*previous['p25']+m)/13
        a25=(D(12)*previous['a25']+abs(m))/13
        p13=(D(6)*previous['p13']+p25)/7
        a13=(D(6)*previous['a13']+a25)/7
        assert a13>0
        tsi=100*p13/a13
        signal=(3*previous['signal7']+tsi)/4
        current={'ts':b['ts'],'close':D(b['close']),'p25':p25,'a25':a25,'p13':p13,'a13':a13,
                 'tsi':tsi,'signal7':signal,'difference':tsi-signal}
        near(m,b['momentum'],'momentum')
        for key in FIELDS:near(current[key],b[key],key)
        assert abs(tsi)<=100+D('0.000000000001')
        flags=event_flags(previous,current)
        assert all(flags[key]is b[key]for key in EVENTS)
        assert(b['source_close_raw']+1)//b['timestamp_scale']==b['ts']+PERIOD
        assert b['source_open_raw']//b['timestamp_scale']==b['ts']
        checked.append(current);previous=current
    return checked

def seed_and_filter(values,length):
    state=None;inputs=[];out=[]
    for value in values:
        if value is None:out.append(None);continue
        if state is None:
            inputs.append(value)
            if len(inputs)==length:state=sum(inputs)/length
        else:state=(state*(length-1)+value*2)/(length+1)
        out.append(state)
    return out

def teaching(evidence):
    for case in evidence['teaching']['given_cases']:
        rows=case['rows'];signals=seed_and_filter([Fraction(b['tsi'])for b in rows],3)
        previous=None
        for row,signal in zip(rows,signals,strict=True):
            expected=None if row['signal_exact']is None else Fraction(row['signal_exact'])
            assert signal==expected
            current={'tsi':Fraction(row['tsi']),'difference':Fraction(row['tsi'])-signal if signal is not None else None}
            flags=event_flags(previous,current)
            assert all(flags[key]is row[key]for key in EVENTS)
            previous=current
    state=evidence['teaching']['zero_before_signal']
    previous=state['previous']
    for row in(state['current'],state['following']):
        expected=(3*Fraction(str(previous['signal7']))+Fraction(str(row['tsi'])))/4
        assert expected==Fraction(str(row['signal7']))
        flags=event_flags(previous,row)
        assert all(flags[key]is row[key]for key in EVENTS)
        previous=row
    flat=evidence['teaching']['flat_continuation']['rows']
    changes=[None]+[Fraction(b['close']-a['close'])for a,b in zip(flat,flat[1:])]
    numerator=seed_and_filter(seed_and_filter(changes,3),2)
    denominator=seed_and_filter(seed_and_filter([abs(x)if x is not None else None for x in changes],3),2)
    for row,n,d in zip(flat,numerator,denominator,strict=True):
        if d is None:assert row['tsi']is None
        else:
            assert d==Fraction(row['denominator_exact'])and n==d and d>0
            assert 100*n/d==row['tsi']==100
    zeros=seed_and_filter(seed_and_filter([None]+[Fraction(0)]*9,3),2)
    assert all(x is None or x==0 for x in zeros)
    assert evidence['teaching']['constant_from_start']['tsi']is None
    assert not any(event_flags({'tsi':-1,'difference':-1},{'tsi':0,'difference':0}).values())
    assert event_flags({'tsi':0,'difference':0},{'tsi':1,'difference':1})['signal_up']
    assert not any(event_flags(None,{'tsi':1,'difference':1}).values())

class DecimalAverage:
    def __init__(self,length):self.length=length;self.inputs=[];self.last=None
    def push(self,value):
        if value is None:return None
        if self.last is None:
            self.inputs.append(value)
            if len(self.inputs)==self.length:self.last=sum(self.inputs)/self.length
        else:self.last=(self.last*(self.length-1)+2*value)/(self.length+1)
        return self.last

def full_reference(path,evidence):
    raw=path.read_bytes();assert sha256(raw).hexdigest()==evidence['provenance']['reference_sha256']
    original=json.loads(raw)
    assert original['protocol_sha256']==evidence['provenance']['reference_protocol_sha256']
    expected={row['ts']:row for row in evidence['context']+evidence['bars']}
    checked=0;previous=None;first_tsi=None;first_signal=None
    a,b,c,d,s=[DecimalAverage(n)for n in(25,25,13,13,7)]
    for index,row in enumerate(original['bars']):
        adjacent=previous is not None and row['ts']==previous['ts']+PERIOD
        if not adjacent:a,b,c,d,s=[DecimalAverage(n)for n in(25,25,13,13,7)]
        change=D(row['close'])-D(previous['close'])if adjacent else None
        signed=c.push(a.push(change));absolute=d.push(b.push(abs(change)if change is not None else None))
        tsi=100*signed/absolute if absolute is not None and absolute>0 else None
        if tsi is None:s=DecimalAverage(7);signal=None
        else:signal=s.push(tsi)
        near(tsi,row['tsi'],'reference core TSI')
        if tsi is not None and first_tsi is None:first_tsi=index+1
        if signal is not None and first_signal is None:first_signal=index+1
        if row['ts']in expected:
            target=expected[row['ts']]
            for key in('open','high','low','close'):assert D(row[key])==D(target[key])
            for key,value in(('p25',a.last),('a25',b.last),('p13',signed),('a13',absolute),
                              ('tsi',tsi),('signal7',signal),('difference',tsi-signal)):
                near(value,target[key],key)
            checked+=1
        previous=row
    assert checked==58 and(first_tsi,first_signal)==(38,44)
    assert len(original['bars'])==evidence['provenance']['full_warmup_bars']==14434
    return {'full_warmup_bars':len(original['bars']),'replayed_context_and_display':checked,'reference_hash':'matched',
            'first_valid_tsi_close':first_tsi,'first_valid_signal_close':first_signal,'first_signal_pair_close':first_signal+1}

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parent=Path(__file__).resolve().parent
    parser.add_argument('--evidence',type=Path,default=parent/'tsi-crossings-guide-evidence.json')
    parser.add_argument('--csv',type=Path,default=parent/'tsi-crossings-guide-candles.csv')
    parser.add_argument('--reference',type=Path)
    args=parser.parse_args();data=json.loads(args.evidence.read_text())
    assert data['schema']=='mpf.tsi-crossings-guide.v1'
    assert len(data['context'])==16 and len(data['bars'])==42
    assert data['bars'][0]['ts']==1704067200 and data['bars'][-1]['ts']==1704657600
    assert data['event_counts']=={key:sum(row[key]for row in data['bars'])for key in EVENTS}
    assert data['event_counts']=={'zero_up':1,'zero_down':1,'signal_up':2,'signal_down':2}
    with localcontext()as context:
        context.prec=50
        values=continuation(data);assert len(values)==58
        teaching(data)
        result={'status':'passed','display_bars':42,'continuation_records':58,'crossing_flags_checked':58*4,
                'given_oscillator_cases':2,'ordering_counterexample':'passed','flat_history_cases':'passed',
                'equality_and_invalid_cases':'passed','event_counts':data['event_counts']}
        if args.reference:result.update(full_reference(args.reference,data))
    if args.csv.is_file():
        rows=list(csv.DictReader(args.csv.open()));assert len(rows)==42
        for row,bar in zip(rows,data['bars'],strict=True):
            for key in('open','high','low','close','source_open_raw','source_close_raw','timestamp_scale'):
                assert row[key]==str(bar[key])
            for key in('opening_utc','available_utc'):assert row[key]==bar[key]
            for key in EVENTS:assert row[key]==str(bar[key])
        result['csv_rows_checked']=42
    print(json.dumps(result,ensure_ascii=False))

if __name__=='__main__':main()
