#!/usr/bin/env python3
"""Independent prefix-sum Envelopes and Decimal50 scaled-Wilder reconstruction."""
import argparse,calendar as cal,datetime as dt,hashlib,io,json,zipfile
from decimal import Decimal as D, localcontext, getcontext
from fractions import Fraction as F
from pathlib import Path
FROZEN='9ab78293f71d19bcdcae6f2d2a68bc597017acd418effc0f52878c1966afbfa1'
STEP=14400;SCALE=1000000
getcontext().prec=50
def epoch(s):return int(dt.datetime.fromisoformat(s.replace('Z','+00:00')).timestamp())
def require(value,message):
    if not value:raise AssertionError(message)
def digest(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()

def reconstruct(rows):
    with localcontext() as ctx:
        ctx.prec=50
        prefix=[0]
        for row in rows:prefix.append(prefix[-1]+row['source_close_int'])
        changes=[];main=[];adx_acc=None;dxs=[];smoothed_sums=None
        for i,row in enumerate(rows):
            h,l,c=[row['source_'+k+'_int'] for k in ('high','low','close')]
            center=F(prefix[i+1]-prefix[i-19],20*SCALE) if i>=19 else None
            up=center*F(201,200) if center is not None else None
            down=center*F(199,200) if center is not None else None
            tr=dp=dm=plus=minus=dx=adx=None
            if i:
                prev=rows[i-1];h0,l0,c0=[prev['source_'+k+'_int'] for k in ('high','low','close')]
                tr=max(h-l,abs(h-c0),abs(l-c0));rise=h-h0;fall=l0-l
                dp=max(rise,0) if rise>fall else 0
                dm=max(fall,0) if fall>rise else 0
                changes.append((tr,dp,dm))
                if i>=14:
                    if smoothed_sums is None:smoothed_sums=[D(sum(v[j] for v in changes[:14])) for j in range(3)]
                    else:smoothed_sums=[old-old/14+D(value) for old,value in zip(smoothed_sums,(tr,dp,dm))]
                    plus=100*smoothed_sums[1]/smoothed_sums[0] if smoothed_sums[0] else D(0)
                    minus=100*smoothed_sums[2]/smoothed_sums[0] if smoothed_sums[0] else D(0)
                    dx=100*abs(plus-minus)/(plus+minus) if plus+minus else D(0)
                    dxs.append(dx)
                    if len(dxs)==14:adx_acc=sum(dxs)
                    elif len(dxs)>14:adx_acc=adx_acc-adx_acc/14+dx
                    adx=adx_acc/14 if adx_acc is not None else None
            adjacent=i>0 and row['ts']-rows[i-1]['ts']==STEP
            ready=adjacent and i>=20
            price=F(c,SCALE);last=main[-1] if main else None
            main.append(dict(sma20=center,upper=up,lower=down,tr=None if tr is None else F(tr,SCALE),dm_plus=None if dp is None else F(dp,SCALE),dm_minus=None if dm is None else F(dm,SCALE),di_plus=plus,di_minus=minus,dx=dx,adx=adx,up_cross=bool(ready and F(rows[i-1]['source_close_int'],SCALE)<=last['upper'] and price>up),down_cross=bool(ready and F(rows[i-1]['source_close_int'],SCALE)>=last['lower'] and price<down),above_upper=None if up is None else price>up,below_lower=None if down is None else price<down,high_touch=None if up is None else F(h,SCALE)>=up,touch_without_close=None if up is None else F(h,SCALE)>=up and price<=up,adx_strong=None if adx is None else adx>=25,full_coverage=row['n']==240 and row['first_ts']==row['ts'] and row['last_ts']==row['ts']+14340))
        return main

def toy(values,spread=200000):
    rows=[]
    for i,c in enumerate(values):
        rows.append(dict(ts=i*STEP,n=240,first_ts=i*STEP,last_ts=i*STEP+14340,source_open_int=c,source_high_int=c+spread,source_low_int=c-spread,source_close_int=c))
    return rows

def synthetic():
    results=[]
    def check(name,value):require(value,name);results.append(dict(name=name,status='passed'))
    flat=toy([1250000]*50,0);x=reconstruct(flat)
    check('SMA20_first_observation20',x[18]['sma20'] is None and x[19]['sma20']==F(5,4))
    check('Envelope_percent_not_price_units',x[19]['upper']==F(1005,800) and x[19]['lower']==F(995,800))
    check('Half_width62_5_pips', (x[19]['upper']-x[19]['sma20'])/F(1,10000)==F(125,2))
    check('Total_width125_pips',(x[19]['upper']-x[19]['lower'])/F(1,10000)==125)
    check('First_transition_needs_predecessor',x[0]['tr'] is None and x[1]['tr']==0)
    check('DI_DX_first_observation15',x[13]['di_plus'] is None and x[14]['di_plus']==0 and x[14]['dx']==0)
    check('ADX_first_observation28',x[26]['adx'] is None and x[27]['adx']==0)
    check('Flat_zero_denominators_defined_zero',all(v['di_plus']==v['di_minus']==v['dx']==v['adx']==0 for v in x[27:]))
    rise=toy([1000000+10000*i for i in range(60)]);r=reconstruct(rise)
    check('Rising_only_DIplus',all(v['di_plus']>0 and v['di_minus']==0 for v in r[14:]))
    check('Rising_only_ADX100',all(v['adx']==100 for v in r[27:]))
    mirror=[dict(v,source_open_int=4000000-v['source_open_int'],source_high_int=4000000-v['source_low_int'],source_low_int=4000000-v['source_high_int'],source_close_int=4000000-v['source_close_int']) for v in rise];m=reconstruct(mirror)
    check('Reflection_swaps_direction_keeps_ADX',all(a['di_plus']==b['di_minus'] and a['adx']==b['adx'] for a,b in zip(r,m)))
    tied=toy([1250000]*50)
    for i,v in enumerate(tied):v['source_high_int']+=i*1000;v['source_low_int']-=i*1000
    t=reconstruct(tied);check('Equal_positive_up_down_both_zero',all(v['dm_plus']==v['dm_minus']==0 for v in t[1:]))
    equality=toy([379900000]*20+[381900000]);eq=reconstruct(equality)
    check('Current_close_equal_upper_is_not_outside',eq[-1]['upper']==F(3819,10) and not eq[-1]['above_upper'] and not eq[-1]['up_cross'])
    equality[-1]['source_high_int']=381900000;eq=reconstruct(equality)
    check('High_equal_upper_counts_as_touch',eq[-1]['high_touch'] and eq[-1]['touch_without_close'])
    cross=toy([379900000]*32+[382000000]+[379900000]*5);a=reconstruct(cross)
    check('Previous_inside_then_close_outside_is_cross',a[32]['up_cross'])
    check('No_cross_before21_observations',not any(v['up_cross'] or v['down_cross'] for v in a[:20]))
    gap=[dict(v) for v in cross]
    for v in gap[32:]:
        for key in ('ts','first_ts','last_ts'):v[key]+=STEP
    g=reconstruct(gap)
    check('Missing_anchor_blocks_cross_only',not g[32]['up_cross'] and g[32]['sma20']==a[32]['sma20'] and g[32]['adx']==a[32]['adx'])
    doubled=[dict(v,**{k:value*2 for k,value in v.items() if k.startswith('source_')}) for v in cross];d=reconstruct(doubled)
    check('Positive_scale_preserves_band_flags_ADX',all(u['up_cross']==v['up_cross'] and ((u['adx'] is None and v['adx'] is None) or (u['adx'] is not None and v['adx'] is not None and abs(u['adx']-v['adx'])<=D('1e-40'))) and (u['sma20'] is None or v['sma20']==2*u['sma20']) for u,v in zip(a,d)))
    prefix=reconstruct(cross[:33]);check('Future_bars_do_not_change_history',a[:33]==prefix)
    check('ADX_threshold_equality_included',D('25')>=25 and not D('24.9999999999')>=25)
    check('Bands_not_one_percent_each_side',x[19]['upper']-x[19]['lower']==x[19]['sma20']/100)
    check('ADX_bounds_and_no_direction_sign',all(v['adx'] is None or 0<=v['adx']<=100 for v in r+m+t+a))
    return results

def main():
    parser=argparse.ArgumentParser();parser.add_argument('--protocol',type=Path,required=True);parser.add_argument('--evidence',type=Path,required=True);parser.add_argument('--raw-dir',type=Path);parser.add_argument('--report',type=Path,required=True);args=parser.parse_args()
    protocol=json.loads(args.protocol.read_text());require(digest(args.protocol)==FROZEN,'Protocol changed');data=json.loads(args.evidence.read_text());require(data['protocol']==protocol and data['protocol_sha256']==FROZEN,'Embedded specification')
    tests=synthetic();expected=reconstruct(data['bars']);numeric=exact=0;largest=D(0)
    for i,(row,wanted) in enumerate(zip(data['bars'],expected,strict=True)):
        for key,value in wanted.items():
            actual=row[key]
            if value is None or isinstance(value,(bool,int)):
                require(actual==value,f'{i}.{key} exact');exact+=1
            else:
                target=D(value.numerator)/D(value.denominator) if isinstance(value,F) else value
                error=abs(D(str(actual))-target);largest=max(largest,error);require(error<=D('1e-10'),f'{i}.{key} numeric');numeric+=1
    used=set()
    for tag,case in zip(('strong','touch','weak'),data['examples'],strict=True):
        candidates=[]
        for i,(row,value) in enumerate(zip(data['bars'],expected)):
            if i in used or row['ts']<1704067200 or not value['full_coverage'] or not expected[i-1]['full_coverage'] or row['ts']-data['bars'][i-1]['ts']!=STEP or value['adx'] is None or value['sma20'] is None:continue
            if tag=='strong' and not (value['up_cross'] and value['adx_strong']):continue
            if tag=='touch' and not (value['touch_without_close'] and value['adx_strong']):continue
            if tag=='weak' and not (value['up_cross'] and not value['adx_strong']):continue
            candidates.append(i)
        require(case['tag']==tag and candidates and case['index']==candidates[0],'First eligible '+tag);i=candidates[0];used.add(i)
        require(case['bars']==data['bars'][i-12:i+10] and case['signal_values']==data['bars'][i] and case['available_ts']==case['signal_ts']+STEP,'Example window');exact+=4
    raw=None
    if args.raw_dir:
        global np,PINS
        import numpy as np
        PINS={x['file']:x['sha256'] for x in protocol['source_manifest']}
        minutes,raw=originals(args.raw_dir,{'warmup_start':protocol['history'][0],'periods':{'all':protocol['history']}});rebuilt=h4_observations(minutes)
        require(len(rebuilt)==len(data['bars']),'Raw H4 count')
        for actual,wanted in zip(data['bars'],rebuilt,strict=True):
            for key in ('ts','n','first_ts','last_ts','source_open_int','source_high_int','source_low_int','source_close_int'):
                require(actual[key]==wanted[key],'Raw H4 '+key);exact+=1
        require(raw['rows']==data['data_quality']['rows'] and raw['exact_duplicate_rows_removed']==data['data_quality']['exact_duplicate_rows_removed'],'Raw quality')
        raw.pop('duplicate_audit',None);raw['h4_bars_reconstructed']=len(rebuilt)
    result=dict(status='passed',protocol_sha256=FROZEN,evidence_sha256=digest(args.evidence),checker_sha256=digest(Path(__file__)),method='Prefix integer sums and exact Fraction bands; Decimal50 scaled Wilder sums; no replay import.',comparison=dict(numeric_values_compared=numeric,exact_values_compared=exact,failures=0,maximum_absolute_error=str(largest)),synthetic_tests=tests,raw_verification=raw,examples_verified=3)
    args.report.parent.mkdir(parents=True,exist_ok=True);args.report.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({k:result[k] for k in ('status','comparison','examples_verified')}))

# Original-minute ZIP normalization and aggregation follow below. These are
# independent from the guide's source-evidence reader and use integer prices.


def price_integer(value):
    pieces = value.split(b".")
    whole = int(pieces[0])
    digits = pieces[1].rstrip(b"0") if len(pieces) == 2 else b""
    require(len(digits) <= 6, "Source precision is finer than 1e-6")
    return whole * SCALE + int((digits + b"000000")[:6])

def originals(folder, protocol):
    """Deduplicate byte-identical source lines before independent aggregation."""
    parts = []
    records = []
    duplicates = []
    backward = []
    raw_count = 0
    day_cache = {}
    first = epoch(protocol["warmup_start"])
    end = max(epoch(window[1]) for window in protocol["periods"].values())
    for name, expected_hash in sorted(PINS.items()):
        path = folder / name
        data = path.read_bytes()
        require(hashlib.sha256(data).hexdigest() == expected_hash, "Pinned ZIP changed: " + name)
        with zipfile.ZipFile(io.BytesIO(data)) as archive:
            require(archive.testzip() is None, "ZIP CRC failure: " + name)
            members = [n for n in archive.namelist() if n.lower().endswith(".csv")]
            require(len(members) == 1 and "GBPUSD" in members[0], "Wrong source CSV identity")
            seen = {}
            lines = archive.read(members[0]).splitlines(keepends=True)
            raw_count += len(lines)
            rows = []
            previous_stamp = None
            for row_number, line in enumerate(lines, 1):
                columns = line.strip().split(b";")
                require(len(columns) == 6, "Expected six source columns")
                stamp = columns[0]
                if previous_stamp is not None and stamp < previous_stamp:
                    backward.append({"file": name, "row": row_number,
                                     "previous_stamp": previous_stamp.decode(), "stamp": stamp.decode()})
                previous_stamp = stamp
                if stamp in seen:
                    old_line, old_number = seen[stamp]
                    require(old_line == line, "Conflicting duplicate timestamp")
                    duplicates.append({"file": name, "first_row": old_number,
                                       "duplicate_row": row_number, "source_stamp": stamp.decode(),
                                       "line_sha256": hashlib.sha256(line).hexdigest()})
                    continue
                seen[stamp] = (line, row_number)
                require(len(stamp) == 15 and stamp[8:9] == b" ", "Invalid timestamp format")
                day = stamp[:8]
                if day not in day_cache:
                    day_cache[day] = cal.timegm((int(day[:4]), int(day[4:6]), int(day[6:8]), 0, 0, 0))
                timestamp = (day_cache[day] + int(stamp[9:11])*3600
                             + int(stamp[11:13])*60 + int(stamp[13:15]) + 18000)
                require(timestamp % 60 == 0, "Source timestamp is not a minute")
                o, h, l, c = [price_integer(x) for x in columns[1:5]]
                require(0 < l <= min(o, c) <= max(o, c) <= h, "Invalid source OHLC")
                if first <= timestamp < end:
                    rows.append((timestamp, o, h, l, c))
            parts.append(np.asarray(rows, dtype=np.int64))
            records.append({"file": name, "sha256": expected_hash, "bytes": len(data),
                            "csv": members[0], "source_rows": len(lines)})
    minutes = np.concatenate(parts)
    minutes = minutes[np.argsort(minutes[:, 0], kind="stable")]
    require(bool(np.all(np.diff(minutes[:, 0]) > 0)), "Retained UTC minutes not unique and ascending")
    return minutes, {"source_files": len(records), "rows": len(minutes),
                     "raw_rows_all_archives": raw_count,
                     "exact_duplicate_rows_removed": len(duplicates),
                     "duplicate_audit": duplicates, "source_backward_jumps": backward,
                     "sources": records, "first_ts": int(minutes[0,0]), "last_ts": int(minutes[-1,0])}

def h4_observations(minutes):
    result = []
    current = None
    for source in minutes:
        timestamp = int(source[0])
        anchor = timestamp - timestamp % STEP
        if current is None or anchor != current["ts"]:
            if current is not None:
                result.append(current)
            current = {"ts": anchor, "source_open_int": int(source[1]),
                       "source_high_int": int(source[2]), "source_low_int": int(source[3]),
                       "source_close_int": int(source[4]), "n": 1,
                       "first_ts": timestamp, "last_ts": timestamp}
        else:
            current["source_high_int"] = max(current["source_high_int"], int(source[2]))
            current["source_low_int"] = min(current["source_low_int"], int(source[3]))
            current["source_close_int"] = int(source[4])
            current["n"] += 1
            current["last_ts"] = timestamp
    if current is not None:
        result.append(current)
    for row in result:
        for field in ("open", "high", "low", "close"):
            row[field] = D(row["source_"+field+"_int"]) / SCALE
    return result

if __name__=="__main__":main()
