#!/usr/bin/env python3
"""Offline independent exact-rational verification of the daily Pivot guide.

Save this script, daily-pivots-guide-evidence.json and
daily-pivots-guide-candles.csv together, then run this script with Python 3.
Optional: --source-zip GBPUSD-M1-2024.zip verifies the retained source minutes.
Only the standard library is needed. No network or project-module imports.
"""
from collections import defaultdict
from datetime import datetime,date,time,timedelta,timezone
from decimal import Decimal
from fractions import Fraction as F
from hashlib import sha256
from pathlib import Path
from zoneinfo import ZoneInfo
import argparse,csv,json,zipfile
UTC=timezone.utc;NY=ZoneInfo('America/New_York');UNIT=1000000
PIN='030b05b4c670c7e152bf4aa4112488c96695d2dcc2b31ca13a3b4834b8431077'
def expected(h,l,c):
 h,l,c=[F(v,UNIT)for v in(h,l,c)];p=(h+l+c)/3;w=h-l
 return dict(p=p,r1=p+(p-l),s1=p-(h-p),r2=p+w,s2=p-w)
def iso(ts):return datetime.fromtimestamp(ts,UTC).isoformat().replace('+00:00','Z')
def epoch(s):return int(datetime.fromisoformat(s.replace('Z','+00:00')).timestamp())
def main():
 here=Path(__file__).resolve().parent;p=argparse.ArgumentParser(description=__doc__)
 p.add_argument('--evidence',type=Path,default=here/'daily-pivots-guide-evidence.json')
 p.add_argument('--csv',type=Path,default=here/'daily-pivots-guide-candles.csv')
 p.add_argument('--source-zip',type=Path);a=p.parse_args();d=json.loads(a.evidence.read_text())
 assert d['protocol']['source_sha256']==d['source']['sha256']==PIN
 minutes=d['minute_records'];assert len(minutes)==8609
 assert all(minutes[i][0]<minutes[i+1][0]for i in range(len(minutes)-1))
 hours=defaultdict(list)
 for ts,o,h,l,c in minutes:
  assert ts%60==0 and 0<l<=min(o,c)<=max(o,c)<=h
  hours[ts//3600*3600].append((ts,o,h,l,c))
 refs=d['references'];calc={}
 for key,r in refs.items():
  day=date.fromisoformat(r['date'])
  if r['definition']=='ny':
   begin=int(datetime.combine(day-timedelta(days=1),time(17),NY).timestamp());end=int(datetime.combine(day,time(17),NY).timestamp())
  else:
   begin=int(datetime.combine(day,time(),UTC).timestamp());end=begin+86400
  assert(r['start'],r['end'])==(begin,end)and(r['start_utc'],r['end_utc'])==(iso(begin),iso(end))
  found=[x for x in minutes if begin<=x[0]<end]
  assert r['n']==len(found)
  if not found:
   assert 'levels_num'not in r and'close_int'not in r;calc[key]=None;continue
  h=max(x[2]for x in found);l=min(x[3]for x in found);c=found[-1][4]
  assert(h,l,c)==(r['high_int'],r['low_int'],r['close_int'])
  assert(r['first_ts'],r['last_ts'])==(found[0][0],found[-1][0])
  out=expected(h,l,c);assert out=={k:F(v,3*UNIT)for k,v in r['levels_num'].items()}
  assert out['r1']-out['s1']==F(h-l,UNIT)and out['r2']-out['s2']==F(2*(h-l),UNIT)
  assert out['s2']<=out['s1']<=out['p']<=out['r1']<=out['r2'];calc[key]=out
 bars=d['bars'];assert len(bars)==120 and len(d['days'])==5
 seen=[];nulls=0
 for di,day in enumerate(d['days']):
  label=date(2024,1,8)+timedelta(days=di);assert day['date']==label.isoformat()
  begin=int(datetime.combine(label-timedelta(days=1),time(17),NY).timestamp());end=int(datetime.combine(label,time(17),NY).timestamp())
  assert(day['start_utc'],day['end_utc'])==(iso(begin),iso(end))
  previous=label-timedelta(days=1)
  while previous.weekday()>4:previous-=timedelta(days=1)
  assert len(day['indices'])==24
  for idx in day['indices']:
   seen.append(idx);r=bars[idx];ts=r['ts'];found=hours[ts]
   assert begin<=ts<end and ts+3600<=end
   assert(r['open_int'],r['high_int'],r['low_int'],r['close_int'])==(found[0][1],max(x[2]for x in found),min(x[3]for x in found),found[-1][4])
   assert r['n']==len(found)and(r['first_utc'],r['last_utc'])==(iso(found[0][0]),iso(found[-1][0]))
   assert(r['anchor_utc'],r['end_utc'])==(iso(ts),iso(ts+3600))
   assert r['ny_reference']=='ny:'+previous.isoformat()
   assert r['utc_reference']=='utc:'+(datetime.fromtimestamp(ts,UTC).date()-timedelta(days=1)).isoformat()
   for kind in('ny','utc'):assert refs[r[kind+'_reference']]['end']<=ts
   nulls+=calc[r['utc_reference']]is None
  assert day['n']==sum(bars[i]['n']for i in day['indices'])
 assert seen==list(range(120))and nulls==2
 assert sum(r['n']for r in bars)==7178 and sum(r['n']==60 for r in bars)==112
 csv_rows=list(csv.DictReader(a.csv.open()));assert len(csv_rows)==240
 for i,r in enumerate(bars):
  for j,kind in enumerate(('ny','utc')):
   row=csv_rows[2*i+j];ref=refs[r[kind+'_reference']]
   assert row['definition']==kind and row['anchor_utc']==r['anchor_utc']and row['end_utc']==r['end_utc']
   assert int(row['n'])==r['n']and int(row['reference_n'])==ref['n']and row['reference_date']==ref['date']
   assert row['reference_start_utc']==ref['start_utc']and row['reference_end_utc']==ref['end_utc']
   for k in('open','high','low','close'):assert F(row[k])==F(r[k+'_int'],UNIT)
   for k in('p','r1','s1','r2','s2'):
    assert(row[k.upper()]==''if calc[ref['key']]is None else F(row[k.upper()])==calc[ref['key']][k])
 s=d['synthetic'];out=expected(s['high_int'],s['low_int'],s['close_int'])
 assert out=={k:F(v,3*UNIT)for k,v in s['levels_num'].items()}
 assert out['p']==F(47825,37500)and out['r1']-out['s1']==F(1,100)
 flat=expected(1275000,1275000,1275000);assert set(flat.values())=={F(51,40)}
 for scale,shift in((2,0),(3,1000000)):
  transformed=expected(scale*s['high_int']+shift,scale*s['low_int']+shift,scale*s['close_int']+shift)
  assert all(transformed[k]==scale*v+F(shift,UNIT)for k,v in out.items())
 for r in d['clocks']:
  ts=int(datetime.combine(date.fromisoformat(r['date']),time(17),NY).timestamp());assert iso(ts)==r['utc']
 assert d['clocks'][0]['utc'].endswith('22:00:00Z')and d['clocks'][1]['utc'].endswith('21:00:00Z')
 # Counterexamples are checked arithmetically, rather than inferred from market OHLC.
 assert F('1.274')<out['p']<F('1.2765')<F('1.2775')
 assert F('1.274')<F('1.275')<F('1.276')
 zip_checked=False
 if a.source_zip:
  assert sha256(a.source_zip.read_bytes()).hexdigest()==PIN
  byts={r[0]:r[1:]for r in minutes};matched={}
  with zipfile.ZipFile(a.source_zip)as z:
   assert z.testzip()is None
   for line in z.open(d['source']['csv']):
    fields=line.decode('ascii').strip().split(';')
    if not '20240104 000000'<=fields[0]<'20240113 000000':continue
    ts=int(datetime.strptime(fields[0],'%Y%m%d %H%M%S').replace(tzinfo=UTC).timestamp())+18000
    if ts in byts:
     prices=[int(Decimal(x)*UNIT)for x in fields[1:5]];assert prices==byts[ts]
     if ts in matched:assert matched[ts]==prices
     matched[ts]=prices
  assert len(matched)==len(minutes);zip_checked=True
 print(json.dumps(dict(status='passed',method='Independent exact rational arithmetic and calendar reconstruction; no project calculation imports',minute_records=len(minutes),h1_bars=len(bars),csv_rows=len(csv_rows),daily_references=len(refs),unavailable_utc_bars=nulls,chronology='Every reference end <= H1 start',original_zip_bytes_checked=zip_checked,synthetic_range_flat_affine_gap_reset_cases='passed')))
if __name__=='__main__':main()
