#!/usr/bin/env python3
"""Separate Aroon25 arithmetic/selection verifier; standard library only.

This program does not import the guide replay or builder. Indicator ages come
from a new reverse scan of each raw integer H/L window, not a deque.
"""
from __future__ import annotations
import argparse
from collections import Counter
from copy import deepcopy
from datetime import datetime, timezone
from decimal import Decimal
import hashlib
import json
from pathlib import Path
import sys

EXPECTED_SOURCE_SHA = '29858fbed84e573a6dbe348c8631bef451dfba6bb481ba49b09075c6a6de5973'
N = 25
STEP = 14400
SCALE = 1000000
SOURCE_FIELDS = ('ts','open','high','low','close','n','first_ts','last_ts',
                 'source_open_int','source_high_int','source_low_int','source_close_int')
# Explicit aliases permit the guide's serialized schema to use descriptive
# names without sharing any production calculation. Every present alias is checked.
FIELD_NAMES = {
 'age_high': ('age_high',), 'age_low': ('age_low',),
 'aroon_up': ('aroon_up','up'), 'aroon_down': ('aroon_down','down'),
 'oscillator': ('oscillator','aroon_oscillator','aroon_osc'),
 'window_high_int': ('window_high_int','highest_high_int','window_high'),
 'window_low_int': ('window_low_int','lowest_low_int','window_low'),
 'high_index': ('high_index','highest_index','high_idx','window_high_index'),
 'low_index': ('low_index','lowest_index','low_idx','window_low_index'),
 'cross_up': ('cross_up','upward_cross','fresh_up_cross'),
 'cross_down': ('cross_down','downward_cross','fresh_down_cross'),
 'adjacent': ('adjacent',),
 'complete_minute_bucket': ('complete_minute_bucket',),
}
REQUIRED_DERIVED = ('age_high','age_low','aroon_up','aroon_down','oscillator',
                    'window_high_int','window_low_int','adjacent','cross_up',
                    'cross_down','complete_minute_bucket')

class Audit:
    def __init__(self):
        self.counts = Counter()
        self.failures = []
        self.failure_count = 0
        self.field_aliases = set()
    def check(self, ok, category, message):
        self.counts[category] += 1
        if not ok:
            self.failure_count += 1
            if len(self.failures) < 40:
                self.failures.append(message)
        return bool(ok)
    def eq(self, actual, expected, category, message):
        # False must not silently equal integer zero; null is never a reading.
        kind_ok = type(actual) is type(expected) or (
            isinstance(actual, (int,float)) and not isinstance(actual,bool)
            and isinstance(expected,(int,float)) and not isinstance(expected,bool))
        return self.check(kind_ok and actual == expected, category,
                          f'{message}: got {actual!r}; expected {expected!r}')

def load_json(path):
    data = Path(path).read_bytes()
    def invalid(value):
        raise ValueError(f'non-JSON numeric constant {value}')
    return json.loads(data, parse_constant=invalid), hashlib.sha256(data).hexdigest()

def derive(bars):
    """Compute from raw H/L only. First equal extreme found in reverse wins."""
    out = []
    for t, bar in enumerate(bars):
        row = {k: None for k in ('age_high','age_low','aroon_up','aroon_down',
                                'oscillator','window_high_int','window_low_int',
                                'high_index','low_index')}
        row.update(cross_up=False, cross_down=False,
                   adjacent=t>0 and bar['ts']-bars[t-1]['ts']==STEP,
                   complete_minute_bucket=complete(bar))
        if t >= N:
            greatest = least = None
            hi = lo = None
            for j in range(t, t-N-1, -1):
                h = bars[j]['source_high_int']
                l = bars[j]['source_low_int']
                if greatest is None or h > greatest:
                    greatest, hi = h, j
                if least is None or l < least:
                    least, lo = l, j
            h_age, l_age = t-hi, t-lo
            up, down = 100 - 4*h_age, 100 - 4*l_age
            row.update(age_high=h_age, age_low=l_age, aroon_up=up,
                       aroon_down=down, oscillator=up-down,
                       window_high_int=greatest, window_low_int=least,
                       high_index=hi, low_index=lo)
            if t > N and bar['ts'] - bars[t-1]['ts'] == STEP:
                before = out[-1]
                row['cross_up'] = before['aroon_up'] <= before['aroon_down'] and up > down
                row['cross_down'] = before['aroon_up'] >= before['aroon_down'] and up < down
        out.append(row)
    return out

def complete(bar):
    return (bar['n']==240 and bar['first_ts']==bar['ts']
            and bar['last_ts']==bar['ts']+STEP-60)

def eligible(bars, i):
    if i < N+1 or i+5 >= len(bars):
        return False
    for j in range(i-26, i+1):
        b = bars[j]
        if j > i-26 and b['ts']-bars[j-1]['ts'] != STEP:
            return False
    return complete(bars[i-1]) and complete(bars[i])

def select_cases(bars, readings, start=1672531200):
    selected = {}
    used = set()
    for kind in ('cross','both_low','both_high'):
        for i,b in enumerate(bars):
            if b['ts'] < start or i in used or not eligible(bars,i):
                continue
            r = readings[i]
            match = (r['cross_up'] if kind == 'cross' else
                     r['aroon_up'] < 50 and r['aroon_down'] < 50 if kind == 'both_low' else
                     r['aroon_up'] > 50 and r['aroon_down'] > 50)
            if match:
                selected[kind] = i
                used.add(i)
                break
        if kind not in selected:
            raise ValueError(f'no eligible {kind} case')
    return selected

def fixture(highs, lows=None):
    if lows is None:
        lows = highs
    return [{'ts':i*STEP,'source_high_int':h,'source_low_int':l,
             'n':240,'first_ts':i*STEP,'last_ts':i*STEP+STEP-60}
            for i,(h,l) in enumerate(zip(highs,lows))]

def edge_tests(a, actual_bars):
    cases = 0
    def test(ok, label):
        nonlocal cases
        cases += 1
        a.check(ok,'edge_case_assertions',label)
    up = derive(fixture(list(range(26))))
    test(all(x['aroon_up'] is None for x in up[:25]),'26-observation warmup: first 25 unavailable')
    test((up[25]['aroon_up'],up[25]['aroon_down']) == (100,0),'age 0 and 25 endpoints')
    test(up[25]['cross_up'] is False,'first line pair cannot itself form a cross')
    down = derive(fixture(list(range(26,0,-1))))[-1]
    test((down['aroon_up'],down['aroon_down']) == (0,100),'decreasing extrema endpoints')
    hs=[150]*26;ls=[50]*26;hs[0]=hs[20]=200;ls[4]=ls[24]=0
    r=derive(fixture(hs,ls))[-1]
    test((r['age_high'],r['age_low'],r['aroon_up'],r['aroon_down'])==(5,1,80,96),'latest equal extrema, not earliest')
    flat=derive(fixture([100]*26))[-1]
    test((flat['aroon_up'],flat['aroon_down'],flat['oscillator'])==(100,100,0),'flat window: 100/100/0')
    old=derive(fixture([200]+[150]*25,[0]+[50]*25))[-1]
    test((old['aroon_up'],old['aroon_down'],old['oscillator'])==(0,0,0),'old outside bar: 0/0/0')
    hs=[150]*26;ls=[50]*26;hs[13]=200;ls[12]=0
    r=derive(fixture(hs,ls))[-1]
    test((r['age_high'],r['age_low'],r['aroon_up'],r['aroon_down'])==(12,13,52,48),'age 12/13 yields 52/48')
    f=fixture([200]+[150]*25+[201],[50]*25+[0,50])
    r=derive(f)
    test(r[25]['cross_up'] is False and r[26]['cross_up'] is True,'cross first testable on observation 27')
    gap=deepcopy(f);gap[-1]['ts']+=STEP
    r_gap=derive(gap)
    test(r_gap[26]['aroon_up']>r_gap[26]['aroon_down'] and not r_gap[26]['cross_up'],'missing H4 anchor invalidates otherwise upward cross')
    f=fixture([200]+[150]*26,[0]*27);r=derive(f)
    test(r[25]['aroon_up']==0 and r[26]['aroon_up']==100 and f[26]['source_high_int']<f[0]['source_high_int'],'expiry lifts Up without exceeding expired high')
    base=fixture(hs,ls);scaled=deepcopy(base)
    for b in scaled:
        b['source_high_int']=b['source_high_int']*7+10001
        b['source_low_int']=b['source_low_int']*7+10001
    rb,rs=derive(base),derive(scaled)
    invariant=('age_high','age_low','aroon_up','aroon_down','oscillator','cross_up','cross_down')
    test(all(all(x[k]==y[k]for k in invariant)for x,y in zip(rb,rs)),'positive price scaling and translation preserve readings')
    vals=list(range(0,101,4))
    test(50 not in vals and 48 in vals and 52 in vals,'50 unavailable at N25')
    for age in range(26):
        test(100-4*age == 4*(25-age),f'exact integer age arithmetic {age}')
    cross_checks=0
    for pu in vals:
        for pd in vals:
            for u in vals:
                for d in vals:
                    a.check((pu<=pd and u>d)==(pu-pd<=0 and u-d>0),
                            'cross_equivalence_checks','upward cross equivalence')
                    a.check((pu>=pd and u<d)==(pu-pd>=0 and u-d<0),
                            'cross_equivalence_checks','downward cross equivalence')
                    cross_checks+=2
    full=derive(actual_bars)
    cuts=sorted(set(x for x in (0,1,24,25,26,27,53,257,len(actual_bars)//2,len(actual_bars)-5,len(actual_bars)) if 0<=x<=len(actual_bars)))
    for cut in cuts:
        test(derive(actual_bars[:cut])==full[:cut],f'prefix independence at {cut} observed candles')
    cut=min(300,len(actual_bars))
    mutated=deepcopy(actual_bars)
    for b in mutated[cut:]:
        b['source_high_int']=10**12
        b['source_low_int']=-10**12
    test(derive(mutated)[:cut]==full[:cut],f'future H/L mutation does not affect first {cut} readings')
    return {'named_assertions':cases,'cross_equivalence_boolean_checks':cross_checks,'prefix_lengths':cuts}

def check_field(a, row, field, expected, where, required=True):
    present=[name for name in FIELD_NAMES[field] if name in row]
    a.check(bool(present) or not required,'schema_fields',f'{where}: missing {field}')
    for name in present:
        a.field_aliases.add(name)
        if field in ('window_high_int','window_low_int') and name in ('window_high','window_low'):
            if expected is None:
                a.eq(row[name],None,'derived_values',f'{where}.{name}')
            else:
                value=row[name]
                ok=type(value)in(int,float) and Decimal(str(value))*SCALE==Decimal(expected)
                a.check(ok,'derived_values',f'{where}.{name}: price {value!r} does not match integer {expected}')
        else:
            if type(expected)is int:
                a.check(type(row[name])is int,'integer_readings',f'{where}.{name} must be an exact integer')
            a.eq(row[name],expected,'derived_values',f'{where}.{name}')

def check_example_row(a, actual, source, calc, where):
    if not a.check(isinstance(actual,dict),'schema_fields',f'{where} must be an object'):
        return
    for key in SOURCE_FIELDS:
        a.eq(actual.get(key),source[key],'selection_context',f'{where}.{key}')
    for key in REQUIRED_DERIVED:
        check_field(a,actual,key,calc[key],where)
    for key in ('high_index','low_index'):
        check_field(a,actual,key,calc[key],where,required=False)


def evidence_bars(evidence):
    for key in ('bars','candles','observations'):
        if isinstance(evidence.get(key),list):
            return key,evidence[key]
    raise ValueError('evidence requires a bars/candles/observations list')

def example_map(evidence):
    raw=evidence.get('examples',evidence.get('cases'))
    if isinstance(raw,dict):
        return raw
    if isinstance(raw,list):
        result={}
        for case in raw:
            key=case.get('tag',case.get('id',case.get('kind',case.get('key'))))
            if key in result:raise ValueError(f'duplicate example key {key}')
            result[key]=case
        return result
    raise ValueError('evidence requires examples/cases dict or list')

def main():
    ap=argparse.ArgumentParser(description=__doc__)
    for key in ('protocol','source-evidence','evidence','report'):
        ap.add_argument('--'+key,required=True,type=Path)
    args=ap.parse_args()
    a=Audit()
    report={'checker':'aroon25-independent-reverse-scan-v1',
            'implementation':'stdlib; reverse raw-integer H/L window scan; no production imports',
            'scope':'pinned existing H4 input, indicator arithmetic, deterministic teaching selection and synthetic edge cases; no M1 reconstruction or strategy profitability',
            'files':{key:str(getattr(args,key.replace('-','_')))for key in ('protocol','source-evidence','evidence')}}
    try:
        protocol,protocol_sha=load_json(args.protocol)
        source,source_sha=load_json(args.source_evidence)
        evidence,evidence_sha=load_json(args.evidence)
        report.update(protocol_sha256=protocol_sha,source_sha256=source_sha,evidence_sha256=evidence_sha)
        a.eq(protocol.get('source_sha256'),EXPECTED_SOURCE_SHA,'hash_pins','protocol source pin')
        a.eq(source_sha,EXPECTED_SOURCE_SHA,'hash_pins','source evidence SHA-256')
        for key,value in [('period',N),('window_observations',N+1),('price_scale',SCALE),('bar_seconds',STEP),('performance_calculated',False)]:
            a.eq(protocol.get(key),value,'protocol_contract',key)
        a.eq(protocol.get('source_fields'),list(SOURCE_FIELDS),'protocol_contract','source fields')
        a.eq(protocol.get('selection',{}).get('order'),['cross','both_low','both_high'],'protocol_contract','case order')
        a.eq(protocol.get('selection',{}).get('start_ts'),1672531200,'protocol_contract','selection start')
        a.eq(protocol.get('selection',{}).get('chart_previous'),25,'protocol_contract','chart previous')
        a.eq(protocol.get('selection',{}).get('chart_following'),5,'protocol_contract','chart following')
        # Root may embed the whole protocol, its hash, or both; verify each present form.
        a.check('protocol' in evidence or 'protocol_sha256' in evidence,'schema_fields','evidence requires protocol or protocol_sha256')
        if 'protocol' in evidence:a.eq(evidence['protocol'],protocol,'embedded_provenance','embedded protocol')
        if 'protocol_sha256' in evidence:a.eq(evidence['protocol_sha256'],protocol_sha,'embedded_provenance','embedded protocol hash')
        if 'source_sha256' in evidence:a.eq(evidence['source_sha256'],source_sha,'embedded_provenance','embedded source hash')
        a.eq(evidence.get('performance_calculated'),False,'protocol_contract','no performance calculated')
        source_bars=source['bars'];bar_key,observed=evidence_bars(evidence)
        a.eq(len(observed),len(source_bars),'source_input','number of H4 inputs')
        for i,b in enumerate(source_bars):
            for key in ('ts','n','first_ts','last_ts','source_open_int','source_high_int','source_low_int','source_close_int'):
                a.check(type(b.get(key))is int,'source_integrity',f'source bar {i}.{key} must be integer')
            a.check(b['ts']%STEP==0,'source_integrity',f'source bar {i} scheduled UTC H4 anchor')
            if i:a.check(b['ts']>source_bars[i-1]['ts'],'source_integrity',f'source chronological order at {i}')
            for key in ('open','high','low','close'):
                a.eq(Decimal(str(b[key]))*SCALE,Decimal(b['source_'+key+'_int']),
                     'source_price_ints',f'source bar {i} {key} integer consistency')
            a.check(b['source_low_int']<=min(b['source_open_int'],b['source_close_int'])
                    <=max(b['source_open_int'],b['source_close_int'])<=b['source_high_int'],
                    'source_integrity',f'source OHLC range at {i}')
            a.check(0<b['n']<=240 and b['ts']<=b['first_ts']<=b['last_ts']<b['ts']+STEP,
                    'source_integrity',f'source minute coverage bounds at {i}')
            if i>=len(observed):continue
            for key in SOURCE_FIELDS:
                a.check(key in observed[i],'schema_fields',f'{bar_key}[{i}] missing source field {key}')
                if key in observed[i]:a.eq(observed[i][key],b[key],'source_input',f'{bar_key}[{i}].{key}')
        calc=derive(source_bars)
        for i,(b,r) in enumerate(zip(observed,calc)):
            for key in REQUIRED_DERIVED:
                check_field(a,b,key,r[key],f'{bar_key}[{i}]')
            for key in ('high_index','low_index'):
                check_field(a,b,key,r[key],f'{bar_key}[{i}]',required=False)
        quality={
            'h4_bars':len(source_bars),
            'partial_h4_bars':sum(b['n']<240 for b in source_bars),
            'incomplete_h4_bars':sum(not complete(b)for b in source_bars),
            'gap_count':sum(source_bars[i]['ts']-source_bars[i-1]['ts']!=STEP for i in range(1,len(source_bars))),
            'first_ts':source_bars[0]['ts'],'last_ts':source_bars[-1]['ts'],
            'source_files':source['data_quality']['source_files']}
        for key,value in quality.items():
            a.eq(evidence.get('data_quality',{}).get(key),value,'data_quality',key)
        report['data_quality']=quality
        teaching=evidence.get('teaching',{})
        expected_table=[{'age':v,'value':100-4*v}for v in (0,1,12,13,25)]
        a.eq(teaching.get('age_table'),expected_table,'teaching','age table')
        tied=teaching.get('tied',{})
        a.eq(tied.get('high_ages'),[25,5],'teaching','tied high input ages')
        a.eq(tied.get('low_ages'),[21,1],'teaching','tied low input ages')
        for key,value in {'age_high':5,'age_low':1,'aroon_up':80,'aroon_down':96,'oscillator':-16}.items():
            a.eq(tied.get(key),value,'teaching','tied.'+key)
        for key,value in {'age_high':0,'age_low':0,'aroon_up':100,'aroon_down':100,'oscillator':0}.items():
            a.eq(teaching.get('flat',{}).get(key),value,'teaching','flat.'+key)
        picked=select_cases(source_bars,calc)
        examples=example_map(evidence)
        a.eq(set(examples),set(picked),'selection','case IDs')
        case_report={}
        for kind,i in picked.items():
            if kind not in examples:continue
            case=examples[kind]
            index=case.get('index',case.get('selected_index',case.get('reference_index')))
            a.eq(index,i,'selection',f'{kind} first qualifying unique index')
            # Bind optional metadata wherever it is explicitly published.
            metadata={'ts':source_bars[i]['ts'],'signal_ts':source_bars[i]['ts'],
                      'available_ts':source_bars[i]['ts']+STEP,'reference_index':25,
                      'start_index':i-25,'end_index':i+5,'chart_start_index':i-25,'chart_end_index':i+5}
            for key,value in metadata.items():
                if key in case:a.eq(case[key],value,'selection',f'{kind}.{key}')
            context=case.get('indices',case.get('chart_indices'))
            if context is not None:a.eq(context,list(range(i-25,i+6)),'selection',f'{kind} chart indices')
            context_bars=case.get('bars',case.get('candles',case.get('context')))
            if isinstance(context_bars,list):
                a.eq(len(context_bars),31,'selection',f'{kind} chart candle count')
                for j,cb in enumerate(context_bars):
                    if j>=31:break
                    expected=source_bars[i-25+j]
                    if isinstance(cb,int):a.eq(cb,i-25+j,'selection',f'{kind} context index {j}')
                    else:
                        check_example_row(a,cb,expected,calc[i-25+j],f'{kind} context {j}')
            else:
                a.check(context is not None or ('start_index' in case and 'end_index' in case)
                        or ('chart_start_index' in case and 'chart_end_index' in case),
                        'schema_fields',f'{kind} requires explicit 25+1+5 chart context')
            a.check(eligible(source_bars,i),'selection',f'{kind} 27 adjacent anchors and complete previous/selected buckets')
            check_example_row(a,case.get('signal_values'),source_bars[i],calc[i],f'{kind}.signal_values')
            check_example_row(a,case.get('previous_values'),source_bars[i-1],calc[i-1],f'{kind}.previous_values')
            for key in ('age_high','age_low','aroon_up','aroon_down','oscillator','window_high_int','window_low_int'):
                if any(name in case for name in FIELD_NAMES[key]):check_field(a,case,key,calc[i][key],kind)
            case_report[kind]={'index':i,'opening_ts':source_bars[i]['ts'],'available_ts':source_bars[i]['ts']+STEP,
                'available_utc':datetime.fromtimestamp(source_bars[i]['ts']+STEP,timezone.utc).isoformat(),
                'chart_indices':[i-25,i+5],
                'earlier_partial_window_buckets':sum(not complete(source_bars[j])for j in range(i-26,i-1)),
                'previous_minute_coverage':{k:source_bars[i-1][k]for k in ('n','ts','first_ts','last_ts')},
                'selected_minute_coverage':{k:source_bars[i][k]for k in ('n','ts','first_ts','last_ts')},**calc[i]}
        a.eq(len(set(picked.values())),3,'selection','unique selected indices')
        report['cases']=case_report
        eligible_upward=[i for i,b in enumerate(source_bars)if b['ts']>=1672531200 and eligible(source_bars,i)and calc[i]['cross_up']]
        old_rule_upward=[i for i in eligible_upward if all(complete(source_bars[j])for j in range(i-26,i+1))]
        report['coverage_revision_check']={
            'revised_rule_eligible_upward_crosses_from_2023':len(eligible_upward),
            'original_all_27_complete_eligible_upward_crosses_from_2023':len(old_rule_upward),
            'uses_future_price_results':False}
        if 'coverage_rule_revision'in protocol:
            a.eq(len(old_rule_upward),0,'coverage_revision','recorded initial all-27-complete rule produced no upward case')
        report['edge_cases']=edge_tests(a,source_bars)
        report['bar_count']=len(source_bars)
        report['defined_reading_count']=max(0,len(source_bars)-N)
        report['strict_upward_cross_count']=sum(r['cross_up']for r in calc)
        report['strict_downward_cross_count']=sum(r['cross_down']for r in calc)
        report['input_ohlc_integer_comparisons']=len(source_bars)*4
        report['derived_aliases_checked']=sorted(a.field_aliases)
    except Exception as exc:
        a.check(False,'execution',f'{type(exc).__name__}: {exc}')
        report['exception']=repr(exc)
    report['status']='passed' if not a.failure_count else 'failed'
    report['checks']=dict(sorted(a.counts.items()))
    report['check_count']=sum(a.counts.values())
    report['failure_count']=a.failure_count
    report['failures']=a.failures
    args.report.parent.mkdir(parents=True,exist_ok=True)
    args.report.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps({k:report[k]for k in ('status','check_count','failure_count')},ensure_ascii=False))
    if a.failures:print('\n'.join(a.failures[:8]),file=sys.stderr)
    return int(bool(a.failure_count))

if __name__=='__main__':
    raise SystemExit(main())
