"""ECON14 actual-source or disclosed public-selection replay.
Cases JSON, model contracts and earlier result files are not numeric inputs.
"""
from pathlib import Path
from fractions import Fraction as F
from collections import Counter
from html.parser import HTMLParser
import csv,hashlib,io,json,re,shutil,subprocess,zipfile
O=Path(__file__).resolve().parent;D=O/'econ14-sources';W=O.parents[1]/'work/textbook-rewrite-2026';A=W/'source-audit-econ14';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 source selection or derived verification target','sha256':hashlib.sha256(p.read_bytes()).hexdigest()};return list(csv.DictReader(p.open(encoding='utf8',newline='')))
def original(p,mode):audit[p.name]={'mode':mode,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()}
def pdf(p):
 if p.exists()and shutil.which('pdftotext'):original(p,'retained original PDF, fresh pdftotext');return subprocess.check_output(['pdftotext','-layout',str(p),'-'],text=True,encoding='utf8').split('\f')
 return None
lfsel=selected('actual-Canada-LFS-November-December2024-historical-release.csv');pages=pdf(A/'StatisticsCanada-LFS-December2024-release.pdf');lfs={}
if pages:
 block=pages[12].split('15 years and over, both sexes')[1].split('15 to 24 years, both sexes')[0]
 for row in lfsel:
  line=re.search(r'^\s*'+re.escape(row['source_label'])+r'\s+([^\n]+)',block,re.M)[1];cells=re.findall(r'-?[\d,]+\.\d|\.\.\.',line)
  for i,k in enumerate(['November2024','December2024']):lfs[row['measure'],k]=F(cells[i].replace(',',''));assert lfs[row['measure'],k]==F(row[k]);checks+=1;originalCells+=1
else:
 audit['LFSFallback']='Public selected historical Table1 values, not complete original replay.'
 for row in lfsel:
  for k in ['November2024','December2024']:lfs[row['measure'],k]=F(row[k])
for(k,t),v in lfs.items():put('country_LFS_'+k+'_'+t,v)
for row in selected('derived-Canada-LFS-denominators-and-published-rounding.csv'):
 t=row['period'];pop,lab,emp,u,full,part=[lfs[k,t]for k in ['population','labour_force','employment','unemployment','full_time_employment','part_time_employment']];assert emp+u==lab;checks+=1
 vals=dict(population_thousand=pop,labour_force_thousand=lab,employed_thousand=emp,unemployed_thousand=u,derived_not_in_labour_force_thousand=pop-lab,unemployment_rate_from_rounded_levels_percent=100*u/lab,participation_rate_from_rounded_levels_percent=100*lab/pop,employment_rate_from_rounded_levels_percent=100*emp/pop,full_plus_part_minus_employment_rounding_thousand=full+part-emp)
 for k,v in vals.items():assert F(row[k])==v;checks+=1;put('country_LFS_'+t+'_'+k,v)
cpsel=selected('actual-Canada-CPI-major-components-NSA-versus-SA.csv');pages=pdf(A/'StatisticsCanada-CPI-December2024-release.pdf');cpi={}
for row in cpsel:
 adjust=row['adjustment'];key=row['category'];values={k:row[k]for k in ['basket_importance_percent','December2023_index','October2024_index','November2024_index','December2024_index','published_month_change_percent','published_year_change_percent']}
 if pages:
  block=pages[6 if adjust=='NSA'else 7].split('All-items',1)[1].split('Special aggregates',1)[0];block='All-items'+block;label='recreational cannabis'if key=='alcohol_tobacco_cannabis'else row['source_label'];line=re.search(r'^\s*'+re.escape(label)+r'\s+([^\n]+)',block,re.M)[1];nums=re.findall(r'-?\d+\.\d+',line)
  names=['basket_importance_percent','December2023_index','November2024_index','December2024_index','published_month_change_percent','published_year_change_percent']if adjust=='NSA'else['October2024_index','November2024_index','December2024_index','unused_previous_month_change','published_month_change_percent']
  for k,v in zip(names,nums):
   if k=='unused_previous_month_change':continue
   assert F(values[k])==F(v);checks+=1;originalCells+=1;values[k]=v
 for k,v in values.items():
  cpi[key,adjust,k]=None if v==''else F(v)
  if v!='':put('country_CPI_'+key+'_'+adjust+'_'+k,F(v))
for row in selected('derived-Canada-CPI-period-and-adjustment-comparisons.csv'):
 k,a=row['category'],row['adjustment'];month=100*(cpi[k,a,'December2024_index']/cpi[k,a,'November2024_index']-1);assert F(row['month_change_from_rounded_levels_percent'])==month;checks+=1;put('country_CPI_'+k+'_'+a+'_derived_month_percent',month)
 if cpi[k,a,'December2023_index']is not None:
  year=100*(cpi[k,a,'December2024_index']/cpi[k,a,'December2023_index']-1);assert F(row['year_change_from_rounded_levels_percent'])==year;checks+=1;put('country_CPI_'+k+'_'+a+'_derived_year_percent',year)

sel=selected('actual9876-ACS2024-Delaware-employment-status-fields.csv');file=W/'source-audit-econ13/Census-ACS2024-1year-Delaware-person.zip';fields=['SERIALNO','SPORDER','STATE','AGEP','ESR','PWGTP']
if file.exists():
 original(file,'retained original ACS ZIP, complete source rows read')
 with zipfile.ZipFile(file)as z:rows=list(csv.DictReader(io.StringIO(z.read('psam_p10.csv').decode('utf-8-sig'))))
 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']='Public necessary6fields, all9876source rows and blanks preserved.'
assert len(rows)==len(sel)==9876
counts=Counter(r['ESR']for r in rows);weights={k:sum(int(r['PWGTP'])for r in rows if r['ESR']==k)for k in ['', '1','2','3','4','5','6']}
for i,r in enumerate(selected('derived-ACS-employment-status-counts-and-person-weights.csv')):
 k=r['source_ESR'];assert int(r['source_rows'])==counts[k]and int(r['person_weight_sum'])==weights[k];checks+=2;put('person_status_'+str(i)+'_rows',counts[k]);put('person_status_'+str(i)+'_weights',weights[k])
empN=counts['1']+counts['2'];unN=counts['3'];labN=empN+unN;civN=labN+counts['6'];emp=weights['1']+weights['2'];u=weights['3'];lab=emp+u;civilian=lab+weights['6']
summary=dict(source_rows=len(rows),source_age16plus_rows=sum(int(r['AGEP'])>=16 for r in rows),source_under16_not_applicable_rows=counts[''],source_armed_forces_rows=counts['4']+counts['5'],civilian_age16plus_source_rows=civN,civilian_employed_source_rows=empN,unemployed_source_rows=unN,civilian_labour_force_source_rows=labN,civilian_not_in_labour_force_source_rows=counts['6'],civilian_population_person_weight=civilian,employed_person_weight=emp,unemployed_person_weight=u,labour_force_person_weight=lab,not_in_labour_force_person_weight=weights['6'],weighted_unemployment_fraction=F(u,lab),weighted_employment_fraction=F(emp,civilian),weighted_participation_fraction=F(lab,civilian),unweighted_unemployment_fraction=F(unN,labN))
target=selected('derived-ACS-civilian16plus-labour-denominators.csv')[0]
for k,v in summary.items():assert F(target[k])==v;checks+=1;put('person_'+k,v)
assert all((int(r['AGEP'])<16)==(r['ESR']=='')for r in rows);checks+=len(rows)

class Body(HTMLParser):
 def __init__(self):super().__init__();self.skip=0;self.text=[]
 def handle_starttag(self,t,a):
  if t in ['head','script','style']:self.skip+=1
 def handle_endtag(self,t):
  if t in ['head','script','style']:self.skip-=1
 def handle_data(self,s):
  if not self.skip:self.text.append(s)
file=W/'source-audit-econ10/Southwest-2024-official10K.html';groups=selected('actual-Southwest2024-active-FTE-composition.csv');stocks=selected('actual-Southwest-employment-stocks-FTE-versus-headcount.csv');values={(r['metric'],r['date']):F(r['amount'])for r in stocks}
if file.exists():
 original(file,'retained original2024annual-report body, scripts/head/style excluded');p=Body();p.feed(file.read_text(encoding='utf8'));body=' '.join(' '.join(p.text).split());parts=body.split('As of December 31, 2024, the Company had ')[1:];block=next(x for x in parts if re.match(r'[\d,]+ active full-time equivalent',x)).split('Labor Union Activity',1)[0]
 active=F(re.match(r'([\d,]+) active full-time equivalent',block)[1].replace(',',''));leave=F(re.search(r'an additional ([\d,]+) Employees as of December 31, 2024',block)[1].replace(',',''));comparison=re.search(r'Active full-time equivalent Employees ([\d,]+) ([\d,]+) \(3.1\) %',body);prior=F(comparison[2].replace(',',''));assert active==F(comparison[1].replace(',',''));checks+=1
 for key,v in [(('active_FTE','2024-12-31'),active),(('active_FTE','2023-12-31'),prior),(('on_leave_employees','2024-12-31'),leave)]:assert values[key]==v;checks+=1;originalCells+=1;values[key]=v
 for row,label in zip(groups,['air operations','ground operations','Customer Representatives','maintenance and engineering','additional']):v=F(re.search(r'([\d,]+) '+label,block)[1].replace(',',''));assert F(row['active_FTE'])==v;checks+=1;originalCells+=1
else:audit['companyFallback']='Public factual FTE/leave source selections; no complete original HTML replay.'
for row in groups:put('company_group_'+row['category']+'_FTE',row['active_FTE'])
for(k,t),v in values.items():put('company_'+k+'_'+t,v)
active=values['active_FTE','2024-12-31'];prior=values['active_FTE','2023-12-31'];leave=values['on_leave_employees','2024-12-31'];assert sum(F(r['active_FTE'])for r in groups)==active;checks+=1
change=selected('derived-Southwest-active-FTE-year-change.csv')[0]
for k,v in [('change_FTE',active-prior),('change_percent_exact',100*(active/prior-1))]:assert F(change[k])==v;checks+=1;put('company_'+k,v)
for i,row in enumerate(selected('hypothetical-Southwest-equal-FTE-different-headcounts.csv')):
 pt=F(row['assumed_part_time_headcount']);ft=active-pt/2;head=ft+pt
 for k,v in [('assumed_full_time_headcount',ft),('fixed_active_FTE',active),('assumed_active_headcount',head),('reported_on_leave_headcount',leave),('assumed_all_employee_headcount',head+leave)]:assert F(row[k])==v;checks+=1;put('hypothetical_'+str(i)+'_'+k,v)
(O/'econ14-results.json').write_text(json.dumps(dict(chapter='ECON-14',metrics=metrics,exactMetrics=exact,inputAudit=audit,originalSourceCellsCompared=originalCells,selectedAndDerivedComparisons=checks,limits='Fixed-vintage rates/rounded levels/SA-NSA, chosen ACS civilian16plus point target and corporate FTE/headcount units. No causal policy tradeoff, national rank, replicate-weight CI or actual PT count inferred.'),ensure_ascii=False,indent=2)+'\n',encoding='utf8');print('ECON14 Python:',len(metrics),'metrics;',checks,'checks;',originalCells,'original fields')
