"""ECON15 independent actual-source/public-selection replay.
No cases JSON, model contract or previous result is a numeric input.
"""
from pathlib import Path
from fractions import Fraction as F
from datetime import date,datetime
from collections import Counter
import csv,hashlib,html,io,json,re,shutil,subprocess,zipfile
O=Path(__file__).resolve().parent;D=O/'econ15-sources';W=O.parents[1]/'work/textbook-rewrite-2026';A=W/'source-audit-econ15'
metrics={};exact={};audit={};checks=0;originalCells=0
def put(k,v):q=F(v);metrics[k]=float(q);exact[k]=str(q)
def selected(n):
 p=D/n;audit[n]={'mode':'public original-source selection or declared derived verification target','sha256':hashlib.sha256(p.read_bytes()).hexdigest()}
 return list(csv.DictReader(p.open(encoding='utf-8-sig',newline='')))
def original(p,mode):audit[p.name]={'mode':mode,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()}
events=selected('actual-bank-rate-change-events.csv');source=A/'BankOfEngland-official-BankRate-history.html'
if source.exists():
 original(source,'retained official HTML parsed independently by row regex');actual={}
 for block in re.findall(r'<tr\b[^>]*>(.*?)</tr>',source.read_text(encoding='utf8'),re.S|re.I):
  text=' '.join(html.unescape(re.sub('<[^>]*>',' ',block)).split());match=re.fullmatch(r'(\d{2} [A-Za-z]{3} \d{2}) (\d+\.\d+)',text)
  if match:actual[datetime.strptime(match[1],'%d %b %y').date().isoformat()]=F(match[2])
 for r in events:assert actual[r['change_date']]==F(r['rate_percent_per_year_source_decimal']);checks+=1;originalCells+=1;r['rate_percent_per_year_source_decimal']=str(actual[r['change_date']])
else:audit['BoEFallback']='Public fixed historical change rows; no live rate retrieval.'
for i,r in enumerate(events):put('country_rate_'+str(i)+'_percent',r['rate_percent_per_year_source_decimal']);assert F(r['rate_fraction_per_year_exact'])==F(r['rate_percent_per_year_source_decimal'])/100;checks+=1
boundaries=[date(2024,1,1)]+[date.fromisoformat(r['change_date'])for r in events if r['change_date'].startswith('2024')]+[date(2025,1,1)]
derived=selected('derived-2024-policy-rate-duration.csv');total=F();daysTotal=0
for i,(start,end)in enumerate(zip(boundaries,boundaries[1:])):
 rate=F(next(r['rate_percent_per_year_source_decimal']for r in reversed(events)if r['change_date']<=start.isoformat()));days=(end-start).days;daysTotal+=days;total+=rate*days
 r=derived[i];assert r['start_inclusive']==start.isoformat()and r['end_exclusive']==end.isoformat();checks+=2
 for k,v in [('calendar_days',days),('annual_policy_rate_percent_exact',rate),('annual_policy_rate_fraction_exact',rate/100),('day_weight_exact',F(days,366)),('rate_times_days_percent_year',rate*days)]:assert F(r[k])==v;checks+=1;put('country_interval_'+str(i)+'_'+k,v)
assert daysTotal==366;put('country_days',daysTotal);put('country_weighted_rate_percent',total/daysTotal);put('hyp_country_simple_actual366_interest_GBP',F(1000)*total/daysTotal/100);put('country_2024_change_percentage_points',F(events[-1]['rate_percent_per_year_source_decimal'])-F(events[-3]['rate_percent_per_year_source_decimal']));put('country_2024_relative_change',(F(events[-1]['rate_percent_per_year_source_decimal'])/F(events[-3]['rate_percent_per_year_source_decimal'])-1))

sel=selected('actual9876-person-INTP-missing-preserved.csv');source=W/'source-audit-econ13/Census-ACS2024-1year-Delaware-person.zip';fields=['STATE','AGEP','PWGTP','ADJINC','INTP','FINTP']
if source.exists():
 original(source,'retained complete original9876-row ACS ZIP')
 with zipfile.ZipFile(source)as z:rows=list(csv.DictReader(io.StringIO(z.read('psam_p10.csv').decode('utf-8-sig'))))
 assert len(rows)==len(sel)==9876
 for i,(r,s)in enumerate(zip(rows,sel),1):
  assert s['source_row_id']==str(i);checks+=1
  for k in fields:assert s[k]==r[k];checks+=1;originalCells+=1
else:rows=sel;audit['ACSFallback']='All9876 public minimal-field positions with blanks, signed INTP and FINTP. No private bank account or original ZIP available.'
categories=['unavailable_under15','negative','zero','positive'];category=lambda r:'unavailable_under15'if r['INTP']==''else'negative'if F(r['INTP'])<0 else'zero'if not F(r['INTP'])else'positive'
summary=selected('actual-person-income-category-summary.csv')
for i,cat in enumerate(categories):
 chosen=[r for r in rows if category(r)==cat];assert all((r['INTP']=='')==(int(r['AGEP'])<15)for r in chosen);checks+=len(chosen)
 values=dict(source_records=len(chosen),person_weight_sum=sum(int(r['PWGTP'])for r in chosen),allocated_records=sum(r['FINTP']=='1'for r in chosen))
 if cat!='unavailable_under15':values['adjusted_income_weighted_sum_exact']=sum(F(r['INTP'])*F(r['ADJINC'])/1000000*int(r['PWGTP'])for r in chosen)
 for k,v in values.items():assert F(summary[i][k])==v;checks+=1;put('person_'+cat+'_'+k,v)
for r,s in zip(rows,sel):
 expected=''if r['INTP']==''else str(F(r['INTP'])*F(r['ADJINC'])/1000000)
 assert s['income_category']==category(r)and s['adjusted_2024_USD_exact']==expected;checks+=2
available=[r for r in rows if r['INTP']!=''];wt=sum(int(r['PWGTP'])for r in available);income=sum(F(r['INTP'])*F(r['ADJINC'])/1000000*int(r['PWGTP'])for r in available)
for k,v in dict(source_records=len(rows),available_records=len(available),available_person_weight=wt,adjusted_income_weighted_total=income,adjusted_income_weighted_mean=income/wt,selected_row4_raw=F(rows[3]['INTP']),selected_row4_adjusted=F(rows[3]['INTP'])*F(rows[3]['ADJINC'])/1000000).items():put('person_'+k,v)
sample=selected('actual-selected-source-row4.csv')[0]
for k in fields:assert sample[k]==rows[3][k];checks+=1

stock=selected('actual-bank-period-end-stocks.csv');flow=selected('actual-bank-annual-interest-flows.csv');source=A/'JPMorganChase-4Q2024-financial-supplement.pdf'
labels=dict(cash_and_due_from_banks='Cash and due from banks',deposits_with_banks='Deposits with banks',gross_loans='Loans',allowance_for_loan_losses='Less: Allowance for loan losses',net_loans='Loans, net of allowance for loan losses',total_assets='TOTAL ASSETS',customer_deposits='Deposits',total_liabilities='TOTAL LIABILITIES',total_equity='TOTAL STOCKHOLDERS\u2019 EQUITY',total_liabilities_equity='TOTAL LIABILITIES AND STOCKHOLDERS\u2019 EQUITY')
if source.exists()and shutil.which('pdftotext'):
 original(source,'retained original PDF, fresh independent page5/6 text extraction');pages=subprocess.check_output(['pdftotext','-layout',str(source),'-'],text=True,encoding='utf8').split('\f');dates=['2024-12-31','2024-09-30','2024-06-30','2024-03-31','2023-12-31'];raw={}
 for k,label in labels.items():
  line=re.search(r'^\s*'+re.escape(label)+r'\s{2,}([^\n]+)',pages[5],re.M)[1];values=[F(v.replace(',',''))for v in re.findall(r'\(?-?\d[\d,]*(?:\.\d+)?\)?',line)[:5]]
  for day,v in zip(dates,values):raw[day,k+'_million_USD']=v
 for r in stock:
  for k in labels:field=k+'_million_USD';assert F(r[field])==raw[r['period_end'],field];r[field]=str(raw[r['period_end'],field]);checks+=1;originalCells+=1
 for key,label in [('interest_income','Interest income'),('interest_expense','Interest expense'),('net_interest_income','Net interest income')]:
  line=re.search(r'^\s*'+re.escape(label)+r'\s{2,}([^\n]+)',pages[4],re.M)[1];values=[F(v.replace(',',''))for v in re.findall(r'\(?-?\d[\d,]*(?:\.\d+)?\)?',line)[-3:-1]]
  for year,v in zip([2024,2023],values):r=next(z for z in flow if int(z['year'])==year);assert F(r[key+'_million_USD'])==v;r[key+'_million_USD']=str(v);checks+=1;originalCells+=1
else:audit['CompanyFallback']='Public necessary consolidated stock/annual-flow selections; no complete PDF extraction.'
for r in stock:
 day=r['period_end'];values={k:F(r[k+'_million_USD'])for k in labels}
 assert values['total_assets']==values['total_liabilities']+values['total_equity']==values['total_liabilities_equity'];assert values['net_loans']==values['gross_loans']-values['allowance_for_loan_losses'];checks+=2
 for k,v in values.items():put('company_'+day+'_'+k,v)
 for k,v in [('loans_to_customer_deposits_exact',values['gross_loans']/values['customer_deposits']),('book_equity_to_assets_exact',values['total_equity']/values['total_assets'])]:assert F(r[k])==v;checks+=1;put('company_'+day+'_'+k,v)
for r in flow:
 assert F(r['interest_income_million_USD'])-F(r['interest_expense_million_USD'])==F(r['net_interest_income_million_USD']);checks+=1
 for k in ['interest_income','interest_expense','net_interest_income']:put('company_'+r['year']+'_'+k,F(r[k+'_million_USD']))

for i,r in enumerate(selected('assumed-interest-only-principal-scenarios.csv')):
 rate=F(r['assumed_annual_simple_rate_exact']);principal=F(800)/rate;assert F(r['hypothetical_principal_USD_exact'])==principal;checks+=1;put('hyp_principal_'+str(i),principal)
for r in selected('assumed-compound-discount-scenarios.csv'):
 n=int(r['year']);factor=F(26,25)**n
 for k,v in [('future_value_USD_exact',1000*factor),('present_value_of_1000_USD_exact',1000/factor),('simple_future_value_USD_exact',1000*(1+n*F(1,25)))]:assert F(r[k])==v;checks+=1;put('hyp_compound_'+str(n)+'_'+k,v)
for i,r in enumerate(selected('assumed-real-rate-scenarios.csv')):
 pi=F(r['assumed_inflation_rate_exact']);gross=F(26,25)/(1+pi)
 for k,v in [('exact_real_gross_factor',gross),('exact_real_net_rate',gross-1),('linear_nominal_minus_inflation',F(1,25)-pi)]:assert F(r[k])==v;checks+=1;put('hyp_real_'+str(i)+'_'+k,v)
toy=selected('assumed-two-bank-T-account-stages.csv');AR,AL,AD,BR,BL,BD=map(F,[200,800,900,300,700,900])
for i,r in enumerate(toy):
 if i==1:AL+=100;AD+=100
 elif i==2:AR-=60;AD-=60;BR+=60;BD+=60
 elif i==3:AL-=40;AD-=40
 values=dict(A_reserves_CU=AR,A_loans_CU=AL,A_deposits_CU=AD,A_equity_CU=100,B_reserves_CU=BR,B_loans_CU=BL,B_deposits_CU=BD,B_equity_CU=100,system_reserves_CU=AR+BR,system_loans_CU=AL+BL,system_deposits_CU=AD+BD)
 assert AR+AL==AD+100 and BR+BL==BD+100;checks+=2
 for k,v in values.items():assert F(r[k])==v;checks+=1;put('hyp_ledger_'+str(i)+'_'+k,v)
(O/'econ15-results.json').write_text(json.dumps(dict(chapter='ECON-15',metrics=metrics,exactMetrics=exact,inputAudit=audit,originalSourceCellsCompared=originalCells,selectedAndDerivedComparisons=checks,limits='Historical policy rates, signed mixed income flows and bank accounting stocks/flows are distinct. Financial scenarios are explicitly assumed; no observed principal, customer rate, causal effect, legal rule or investment advice identified.'),ensure_ascii=False,indent=2)+'\n',encoding='utf8');print('ECON15 Python:',len(metrics),'metrics;',checks,'checks;',originalCells,'original fields')
