#!/usr/bin/env python3
"""Standalone percentage-Envelopes/Wilder-ADX guide replay; standard library only."""
import argparse, hashlib, json
from collections import deque
from decimal import Decimal as D, localcontext
from fractions import Fraction as F
from pathlib import Path

FROZEN = '9ab78293f71d19bcdcae6f2d2a68bc597017acd418effc0f52878c1966afbfa1'
STEP = 14400
SCALE = 1000000
BASE = ('ts','open','high','low','close','n','first_ts','last_ts','source_open_int','source_high_int','source_low_int','source_close_int')


def digest(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def measures(source):
    rows=[]; closes=deque(maxlen=20); transitions=deque(maxlen=14)
    smoothed=None; dx_seed=[]; adx=None; previous=None; prior_upper=prior_lower=None
    with localcontext() as ctx:
        ctx.prec=40
        for original in source:
            b={k:original[k] for k in BASE}
            o,h,l,c=[b['source_'+k+'_int'] for k in ('open','high','low','close')]
            assert 0<l<=min(o,c)<=max(o,c)<=h
            closes.append(c)
            sma=F(sum(closes),20*SCALE) if len(closes)==20 else None
            upper=sma*F(201,200) if sma is not None else None
            lower=sma*F(199,200) if sma is not None else None
            values=dict.fromkeys(('tr','dm_plus','dm_minus','di_plus','di_minus','dx','adx'))
            if previous is not None:
                ph,pl,pc=[previous['source_'+k+'_int'] for k in ('high','low','close')]
                tr=max(h-l,abs(h-pc),abs(l-pc));up=h-ph;down=pl-l
                dp=up if up>down and up>0 else 0
                dm=down if down>up and down>0 else 0
                transition=(tr,dp,dm);transitions.append(transition)
                values.update(tr=tr/SCALE,dm_plus=dp/SCALE,dm_minus=dm/SCALE)
                if len(transitions)==14:
                    if smoothed is None:
                        smoothed=[sum(D(r[k]) for r in transitions)/14 for k in range(3)]
                    else:
                        smoothed=[(13*x+D(v))/14 for x,v in zip(smoothed,transition)]
                    plus=100*smoothed[1]/smoothed[0] if smoothed[0] else D(0)
                    minus=100*smoothed[2]/smoothed[0] if smoothed[0] else D(0)
                    dx=100*abs(plus-minus)/(plus+minus) if plus+minus else D(0)
                    if adx is None:
                        dx_seed.append(dx)
                        if len(dx_seed)==14:adx=sum(dx_seed)/14
                    else:adx=(13*adx+dx)/14
                    values.update(di_plus=plus,di_minus=minus,dx=dx,adx=adx)
            adjacent=previous is not None and b['ts']-previous['ts']==STEP
            ready=adjacent and all(v is not None for v in (sma,prior_upper,prior_lower))
            price=F(c,SCALE)
            b.update(sma20=None if sma is None else float(sma),upper=None if upper is None else float(upper),lower=None if lower is None else float(lower),**{k:None if v is None else float(v) for k,v in values.items()})
            b.update(up_cross=bool(ready and F(previous['source_close_int'],SCALE)<=prior_upper and price>upper),down_cross=bool(ready and F(previous['source_close_int'],SCALE)>=prior_lower and price<lower),above_upper=None if upper is None else price>upper,below_lower=None if lower is None else price<lower,high_touch=None if upper is None else F(h,SCALE)>=upper,touch_without_close=None if upper is None else F(h,SCALE)>=upper and price<=upper,adx_strong=None if adx is None else adx>=25,full_coverage=b['n']==240 and b['first_ts']==b['ts'] and b['last_ts']==b['ts']+14340)
            rows.append(b);previous=b;prior_upper=upper;prior_lower=lower
    return rows


def select_examples(rows):
    used=set();examples=[]
    for tag in ('strong','touch','weak'):
        for i,b in enumerate(rows):
            if b['ts']<1704067200 or i in used or not b['full_coverage'] or not rows[i-1]['full_coverage'] or b['ts']-rows[i-1]['ts']!=STEP or b['adx'] is None or b['sma20'] is None:continue
            if tag=='strong' and not (b['up_cross'] and b['adx_strong']):continue
            if tag=='touch' and not (b['touch_without_close'] and b['adx_strong']):continue
            if tag=='weak' and not (b['up_cross'] and not b['adx_strong']):continue
            used.add(i);examples.append(dict(tag=tag,index=i,signal_ts=b['ts'],available_ts=b['ts']+STEP,signal_values=b,previous_values=rows[i-1],bars=rows[i-12:i+10]));break
        else:raise ValueError('No qualifying example for '+tag)
    return examples


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--protocol',type=Path,required=True)
    parser.add_argument('--source-evidence',type=Path,required=True)
    parser.add_argument('--output',type=Path,required=True)
    args=parser.parse_args();protocol=json.loads(args.protocol.read_text())
    assert digest(args.protocol)==FROZEN
    assert digest(args.source_evidence)==protocol['source_sha256']
    source=json.loads(args.source_evidence.read_text());bars=measures(source['bars'])
    quality={k:source['data_quality'][k] for k in ('source_files','sources','rows','raw_rows_all_archives','exact_duplicate_rows_removed','h4_bars','partial_h4_bars','stale_close_h4_bars','first_ts','last_ts')}
    data=dict(protocol=protocol,protocol_sha256=FROZEN,data_quality=quality,bars=bars,examples=select_examples(bars),teaching=protocol['teaching'],performance_calculated=False)
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.output.write_text(json.dumps(data,ensure_ascii=False,separators=(',',':'))+'\n')
    print(json.dumps(dict(status='passed',bars=len(bars),examples=[{k:c[k] for k in ('tag','available_ts')} for c in data['examples']],data_quality={k:v for k,v in quality.items() if k!='sources'})))


if __name__=='__main__':main()
