#!/usr/bin/env python3
"""Rebuild equivalent range-position oscillators; no trading simulation."""
import argparse,hashlib,json
from collections import Counter
from decimal import Decimal
from fractions import Fraction
from pathlib import Path
FROZEN="3bf65c70f998363ebc9c89c676a4af8839c3e0de972c70145cc6de5f35a46f6f"
STEP=14400;SCALE=100000000;PERIOD=14
BASE=('ts','open','high','low','close','volume','source_close_raw','timestamp_scale','canonical')
sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()

def calculate(source):
    rows=[];segment=[];ratios=[]
    for original in source:
        row={key:original[key]for key in BASE}
        prices={key:int(Decimal(str(row[key]))*SCALE)for key in('open','high','low','close')}
        assert all(Decimal(str(row[k]))*SCALE==v for k,v in prices.items())
        assert 0<prices['low']<=min(prices['open'],prices['close'])<=max(prices['open'],prices['close'])<=prices['high']
        assert type(row['ts'])is int and row['ts']%STEP==0 and row['timestamp_scale']in(1000,1000000)
        assert row['canonical']==(row['source_close_raw']==(row['ts']+STEP)*row['timestamp_scale']-1)
        for key in('high','low','close'):assert prices[key]==original[key+'_int']
        if rows:assert row['ts']>rows[-1]['ts']and(row['ts']-rows[-1]['ts'])%STEP==0
        adjacent=bool(rows and row['ts']-rows[-1]['ts']==STEP)
        if not adjacent or not row['canonical']:segment=[]
        if row['canonical']:segment.append(prices)
        segment=segment[-PERIOD:]
        lo=hi=wr=raw=None
        if len(segment)==PERIOD:
            lo=min(x['low']for x in segment);hi=max(x['high']for x in segment)
            if hi>lo:
                wr=Fraction(-100*(hi-prices['close']),hi-lo)
                raw=Fraction(100*(prices['close']-lo),hi-lo)
                assert wr==raw-100
        previous=ratios[-1]if ratios else None
        cross=bool(adjacent and previous is not None and wr is not None and previous<=-80<wr)
        row.update({'source_'+key+'_int':value for key,value in prices.items()})
        row.update(low14=None if lo is None else lo/SCALE,high14=None if hi is None else hi/SCALE,
                   wr=None if wr is None else float(wr),raw_k=None if raw is None else float(raw),
                   wr_numerator=None if wr is None else wr.numerator,wr_denominator=None if wr is None else wr.denominator,
                   raw_k_numerator=None if raw is None else raw.numerator,raw_k_denominator=None if raw is None else raw.denominator,
                   low_cross=cross,low_zone=None if wr is None else wr<-80,high_zone=None if wr is None else wr>-20,
                   rising_below=bool(adjacent and previous is not None and wr is not None and previous<wr<-80))
        ratios.append(wr);rows.append(row)
    return rows

def select(rows,protocol):
    selected=[];used=set();start=protocol['selection']['start_ts']
    for tag in protocol['selection']['order']:
        for i,row in enumerate(rows):
            if row['ts']<start or i<25 or i in used or i+5>=len(rows):continue
            window=rows[i-16:i+1]
            if not all(r['canonical']for r in window):continue
            if any(b['ts']-a['ts']!=STEP for a,b in zip(window,window[1:])):continue
            if tag=='low_cross'and not row['low_cross']:continue
            if tag=='low_zone'and not row['rising_below']:continue
            if tag=='high_run'and not all(r['high_zone']is True for r in rows[i-3:i+1]):continue
            used.add(i);selected.append(dict(tag=tag,index=i,signal_ts=row['ts'],available_ts=row['ts']+STEP,
                reference_index=25,signal_values=row,previous_values=rows[i-1],bars=rows[i-25:i+6]));break
        else:raise ValueError('No example for frozen predicate: '+tag)
    return selected

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--protocol',type=Path,required=True);p.add_argument('--source-evidence',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    protocol=json.loads(a.protocol.read_text());assert sha(a.protocol)==FROZEN;assert protocol['period']==PERIOD and protocol['window_observations']==PERIOD
    assert sha(a.source_evidence)==protocol['source_sha256']
    source=json.loads(a.source_evidence.read_text());rows=calculate(source['bars'])
    gaps=[dict(left=a['ts'],right=b['ts'],missing=(b['ts']-a['ts'])//STEP-1)for a,b in zip(rows,rows[1:])if b['ts']-a['ts']>STEP]
    quality=dict(rows=len(rows),source_files=len(protocol['source_manifest']),gaps=gaps,missing_bars=sum(x['missing']for x in gaps),
        noncanonical_closes=[r['ts']for r in rows if not r['canonical']],timestamp_units=dict(Counter(str(r['timestamp_scale'])for r in rows)),
        first_ts=rows[0]['ts'],last_ts=rows[-1]['ts'],defined_readings=sum(r['wr']is not None for r in rows))
    data=dict(protocol=protocol,protocol_sha256=sha(a.protocol),data_quality=quality,bars=rows,examples=select(rows,protocol),
              teaching=protocol['teaching'],performance_calculated=False)
    a.output.parent.mkdir(parents=True,exist_ok=True);a.output.write_text(json.dumps(data,ensure_ascii=False,separators=(',',':'))+'\n')
    print(json.dumps({'status':'passed','quality':quality,'examples':[{k:c[k]for k in('tag','index','available_ts')}for c in data['examples']]}))
if __name__=='__main__':main()
