#!/usr/bin/env python3
"""Replay Aroon25 observations and deterministic educational examples.

The pinned source was published for an earlier strategy. This guide computes
indicator readings only; it creates no orders or account returns.
"""
import argparse
from collections import deque
from decimal import Decimal
from hashlib import sha256
import json
from pathlib import Path

BASE = ('ts','open','high','low','close','n','first_ts','last_ts',
        'source_open_int','source_high_int','source_low_int','source_close_int')
N = 25
STEP = 14400

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

def calculate(source):
    highest, lowest = deque(), deque()
    rows = []
    for i, original in enumerate(source):
        row = {key: original[key] for key in BASE}
        assert isinstance(row['ts'], int) and row['ts'] % STEP == 0
        assert 0 < row['n'] <= 240
        assert row['ts'] <= row['first_ts'] <= row['last_ts'] < row['ts'] + STEP
        if rows:
            assert row['ts'] > rows[-1]['ts'] and (row['ts']-rows[-1]['ts']) % STEP == 0
        for field in ('open','high','low','close'):
            assert Decimal(str(row[field])) * 1000000 == row['source_'+field+'_int']
        assert 0 < row['source_low_int'] <= min(row['source_open_int'],row['source_close_int'])
        assert max(row['source_open_int'],row['source_close_int']) <= row['source_high_int']
        # Equality discards the older occurrence: latest equal extremes win.
        while highest and source[highest[-1]]['source_high_int'] <= row['source_high_int']:
            highest.pop()
        while lowest and source[lowest[-1]]['source_low_int'] >= row['source_low_int']:
            lowest.pop()
        highest.append(i); lowest.append(i)
        while highest[0] < i-N: highest.popleft()
        while lowest[0] < i-N: lowest.popleft()
        values = {key: None for key in ('age_high','age_low','aroon_up','aroon_down',
                                        'oscillator','window_high','window_low')}
        if i >= N:
            ah, al = i-highest[0], i-lowest[0]
            up, down = 4*(N-ah), 4*(N-al)
            values.update(age_high=ah,age_low=al,aroon_up=up,aroon_down=down,
                          oscillator=up-down,window_high=source[highest[0]]['high'],
                          window_low=source[lowest[0]]['low'])
        adjacent = bool(i and row['ts']-rows[-1]['ts'] == STEP)
        ready = bool(i >= N+1 and adjacent)
        up_cross = bool(ready and rows[-1]['aroon_up'] <= rows[-1]['aroon_down']
                        and values['aroon_up'] > values['aroon_down'])
        down_cross = bool(ready and rows[-1]['aroon_up'] >= rows[-1]['aroon_down']
                          and values['aroon_up'] < values['aroon_down'])
        row.update(values, adjacent=adjacent, cross_up=up_cross, cross_down=down_cross,
                   complete_minute_bucket=bool(row['n']==240 and row['first_ts']==row['ts']
                                               and row['last_ts']==row['ts']+STEP-60))
        rows.append(row)
    return rows

def select_examples(rows, protocol):
    used = set()
    examples = []
    for tag in protocol['selection']['order']:
        for i, row in enumerate(rows):
            if row['ts'] < protocol['selection']['start_ts'] or i in used or i < 26 or i+5 >= len(rows):
                continue
            window = rows[i-26:i+1]
            if not all(b['complete_minute_bucket'] for b in window[-2:]): continue
            if any(b['ts']-a['ts'] != STEP for a,b in zip(window,window[1:])): continue
            if tag == 'cross' and not row['cross_up']: continue
            if tag == 'both_low' and not (row['aroon_up'] < 50 and row['aroon_down'] < 50): continue
            if tag == 'both_high' and not (row['aroon_up'] > 50 and row['aroon_down'] > 50): continue
            used.add(i)
            examples.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 eligible example under the declared rules: '+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 protocol['period']==25 and protocol['window_observations']==26
    assert digest(args.source_evidence)==protocol['source_sha256']
    source=json.loads(args.source_evidence.read_text())
    rows=calculate(source['bars'])
    examples=select_examples(rows,protocol)
    quality=dict(h4_bars=len(rows),partial_h4_bars=sum(b['n']<240 for b in rows),
                 incomplete_h4_bars=sum(not b['complete_minute_bucket'] for b in rows),
                 gap_count=sum(b['ts']-a['ts']!=STEP for a,b in zip(rows,rows[1:])),
                 first_ts=rows[0]['ts'],last_ts=rows[-1]['ts'],
                 source_files=source['data_quality']['source_files'])
    teaching=dict(age_table=[dict(age=age,value=4*(25-age))for age in (0,1,12,13,25)],
                  tied=dict(high_ages=[25,5],low_ages=[21,1],age_high=5,age_low=1,
                            aroon_up=80,aroon_down=96,oscillator=-16),
                  flat=dict(age_high=0,age_low=0,aroon_up=100,aroon_down=100,oscillator=0))
    evidence=dict(protocol=protocol,protocol_sha256=digest(args.protocol),
                  data_quality=quality,bars=rows,examples=examples,teaching=teaching,
                  performance_calculated=False)
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.output.write_text(json.dumps(evidence,ensure_ascii=False,separators=(',',':'))+'\n')
    print(json.dumps(dict(status='passed',quality=quality,
                         examples=[{k:c[k]for k in ('tag','index','available_ts')}for c in examples])))

if __name__=='__main__':
    main()
