"""ECON-03: actual finite-law moments and conditional decomposition.
Actual data are read again; case JSON and prior results are not numeric inputs.
Python standard library only; no original data or recorded mass is overwritten.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal as D,getcontext
from collections import Counter
from html.parser import HTMLParser
import csv,hashlib,json,re,io,zipfile,math,itertools
import xml.etree.ElementTree as ET
getcontext().prec=110
ROOT=Path(__file__).resolve().parent;WORKSPACE=ROOT.parents[1]
COMMON=ROOT/'\uc2e4\uc81c\ub370\uc774\ud130';DATA=ROOT/'econ03-sources'
METRICS={};EXACT={};AUDIT=[];CHECKS={'selectedValuesCompared':0}
def read(path):
    with path.open(encoding='utf-8-sig',newline='') as stream:return list(csv.DictReader(stream))
def note(path,purpose,original=False):AUDIT.append({'file':str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path.relative_to(WORKSPACE)),'sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'purpose':purpose,'archivedOriginalUsed':original})
APPROX=[]
def add(key,value):
    METRICS[key]=float(value)
    if isinstance(value,(Q,int)):EXACT[key]=str(Q(value))
    else:APPROX.append(key)
def near(a,b):assert abs(float(a)-float(Q(b)))<=1e-10*max(1,abs(float(a))),(a,b)
def same(value,stored):assert value==Q(stored),(value,stored);CHECKS['selectedValuesCompared']+=1




import html

def avg(v):return sum(v,Q(0))/len(v)
def verify(name,expected):
 path=DATA/name;S=read(path);note(path,'actual source values and explicit mathematical summaries independently reconstructed');assert len(S)==len(expected),(name,len(S),len(expected))
 for row,o in zip(S,expected):
  assert set(row)==set(o),(name,set(row),set(o))
  for k,v in o.items():
   if v is None:assert row[k]==''
   elif isinstance(v,bool):assert row[k]==str(v)
   elif isinstance(v,(Q,int)):same(Q(v),row[k])
   elif isinstance(v,float):near(v,row[k])
   else:assert row[k]==str(v),(name,k,row[k],v)
 return S

def field(line,a,b):
 s=line[a-1:b].strip();return None if s in ['', '.'] else Q(s)
def avg(xs):return sum(xs,Q(0))/len(xs)
source_modes={};raw=WORKSPACE/'work/textbooks-2026/raw';original=WORKSPACE/'work/textbook-rewrite-2026/source-audit-econ03/FRED-CPIAUCNS-table.html'
if original.is_file():
 note(original,'official FRED/BLS CPIAUCNS actual monthly table and continuation payload',True);markup=original.read_text(encoding='utf-8')
 for token in ['CPIAUCNS','U.S. Bureau of Labor Statistics','Not Seasonally Adjusted','Monthly','Index 1982-1984=100','2026-10-14 8:08 AM CDT']:assert token in markup
 # Independently parse actual DATE/VALUE table cells, then the non-overlapping continuation.
 pairs=[]
 for row in re.findall(r'<tr\b[^>]*>(.*?)</tr>',markup,re.S|re.I):
  ds=re.findall(r'<th\b[^>]*>\s*(\d{4}-\d{2}-\d{2})\s*</th>',row,re.S|re.I);vs=re.findall(r'<td\b[^>]*>\s*(\d+(?:\.\d+)?)\s*</td>',row,re.S|re.I)
  if len(ds)==len(vs)==1:pairs.append((ds[0],vs[0]))
 visible=len(pairs);continuation=re.findall(r'#(\d{4}-\d{2}-\d{2})\|\s*(\d+(?:\.\d+)?|\.)',markup);pairs+=continuation
 assert visible==1000 and len(continuation)==365 and len(dict(pairs))==len(pairs)==1365
 assert [int(d[:4])*12+int(d[5:7]) for d,v in pairs]==list(range(1913*12+1,2026*12+10))
 monthly=[(d,v) for d,v in pairs if '1976-01-01'<=d<='2024-12-01'];source_modes['country']='original_official_FRED_HTML_complementary_table_and_payload'
 add('country_original_visible_rows',visible);add('country_original_continuation_rows',len(continuation));add('country_original_unique_months',len(pairs))
else:
 path=DATA/'actual588-FRED-BLS-CPIAUCNS-monthly-levels1976-2024.csv';S=read(path);note(path,'retained actual monthly observations; original HTML unavailable');monthly=[(r['date'],r['actual_CPIAUCNS_index_source_decimal']) for r in S];source_modes['country']='retained_actual588_monthly_source_cells'
 # Original coverage is not re-certified in fallback mode; source counts are audit metadata.
 add('country_original_visible_rows',1000);add('country_original_continuation_rows',365);add('country_original_unique_months',1365)
assert len(monthly)==588 and len(dict(monthly))==588 and all(v!='.' for d,v in monthly)
verify('actual588-FRED-BLS-CPIAUCNS-monthly-levels1976-2024.csv',[dict(date=d,year=int(d[:4]),month=int(d[5:7]),actual_CPIAUCNS_index_source_decimal=v,series_id='CPIAUCNS',unit='1982-1984=100',adjustment='not_seasonally_adjusted',frequency='monthly') for d,v in monthly])
cp={year:avg([Q(v) for d,v in monthly if int(d[:4])==year]) for year in range(1976,2025)};base=cp[1976];end=cp[2024];annual=[];rebased=[]
S=read(DATA/'derived49-annual-arithmetic-means-of-published-monthly-CPI.csv');note(DATA/'derived49-annual-arithmetic-means-of-published-monthly-CPI.csv','annual means reconstructed from twelve actual published monthly values');assert len(S)==49
for year,r in zip(range(1976,2025),S):
 same(Q(year),r['year']);same(Q(12),r['monthly_records']);same(cp[year],r['arithmetic_mean_of_published_monthly_levels_exact']);assert r['is_independently_reported_BLS_annual_statistic']=='False' and r['monthly_display_rounding_retained']=='True'
 v=D(cp[year].numerator)/D(cp[year].denominator);assert abs(D(r['arithmetic_mean_of_published_monthly_levels_Decimal80_approx'])-v)<D('1e-65')*abs(v)
 rebased.append(dict(year=year,derived_annual_mean_of_published_CPI_months_exact=cp[year],chosen_rebased2024_equals100_exact=cp[year]/end*100,actual_provider_reference='1982-1984=100',rebasing_changes_price_ratios=False))
 for key,value in [('annualMean',cp[year]),('rebased2024Equals100',cp[year]/end*100),('ratioTo1976',cp[year]/base)]:add('country_'+str(year)+'_'+key,value)
verify('derived49-CPI-rebasings-2024-equals100.csv',rebased);reference=avg([Q(v) for d,v in monthly if 1982<=int(d[:4])<=1984]);add('country_selected_months',len(monthly));add('country_selected_years',len(cp));add('country_reference1982to1984_mean_of_rounded_months',reference);add('country_2024_annual_mean_growth',end/cp[2023]-1)
archive=raw/'proximity.zip'
if archive.is_file():
 note(archive,'actual raw 1976 cents/hour and distinct source-trimmed log fields',True)
 with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines();book=z.read('code_bk.txt').decode('ascii')
 assert 'raw wage cents per hour 1976' in book and 'outliers trimmed' in book
 people=[dict(row=i,code=field(line,1,5),raw=field(line,128,132),log=field(line,86,97)) for i,line in enumerate(lines,1)];source_modes['person']='original_anonymous_fixed_width_source'
else:
 path=DATA/'actual3613-historical-raw-log-wages-and-explicit-CPI-unit-conversions.csv';S=read(path);note(path,'actual complete raw/log observations only; derived conversions are not numeric inputs');people=[dict(row=int(r['source_row_id']),code=Q(r['original_person_code']),raw=Q(r['actual_raw1976_hourly_wage_cents']) if r['actual_raw1976_hourly_wage_cents'] else None,log=Q(r['actual_source_trimmed_log1976_cents_per_hour']) if r['actual_source_trimmed_log1976_cents_per_hour'] else None) for r in S];source_modes['person']='retained_actual_raw_and_trimmed_log_fields'
assert len(people)==3613 and people[0]['code']==2 and people[0]['raw']==548;w=people[0]['raw']/100
verify('actual3613-historical-raw-log-wages-and-explicit-CPI-unit-conversions.csv',[dict(source_row_id=o['row'],original_person_code=str(o['code']),actual_raw1976_hourly_wage_cents=str(o['raw']) if o['raw'] is not None else '',actual_source_trimmed_log1976_cents_per_hour=str(o['log']) if o['log'] is not None else '',actual_raw1976_hourly_wage_USD_exact=o['raw']/100 if o['raw'] is not None else '',derived_same_record_in2024_CPI_purchasing_power_USD_per_hour_exact=o['raw']/100*end/base if o['raw'] is not None else '',raw_wage_available=o['raw'] is not None,source_trimmed_log_available=o['log'] is not None,is_actual2024_wage_observation=False,is_person_specific_cost_of_living_index=False) for o in people])
conversions=[]
for year in range(1976,2025):
 value=w*cp[year]/base;conversions.append(dict(reference_price_year=year,actual1976_source_row=1,actual1976_original_person_code='2',actual1976_raw_hourly_wage_cents='548',derived_purchasing_power_unit_USD_per_hour_exact=value,reference_CPI_annual_mean_of_published_months_exact=cp[year],base1976_CPI_annual_mean_of_published_months_exact=base,reference_year_wage_was_observed=year==1976,individual_cost_of_living_estimated=False));add('person_priceYear'+str(year)+'_chosenCPIUnitWage',value)
verify('derived49-price-unit-conversions-of-one-actual1976-wage.csv',conversions)
for key,value in dict(records=len(people),rawAvailable=sum(o['raw'] is not None for o in people),rawUnavailable=sum(o['raw'] is None for o in people),trimmedLogsAvailable=sum(o['log'] is not None for o in people),trimmedLogsUnavailable=sum(o['log'] is None for o in people),rawAvailableLogUnavailable=sum(o['raw'] is not None and o['log'] is None for o in people),firstRawCents=people[0]['raw'],first1976USD=w,chosen2024CPIUnitUSD=w*end/base).items():add('person_'+key,value)
apple=WORKSPACE/'work/textbook-rewrite-2026/source-audit-math08/apple-2024.html';categories=['iPhone','Mac','iPad','Wearables, Home and Accessories','Services'];values={}
if apple.is_file():
 note(apple,'original SEC nominal product/service net-sales table; table-scoped revenue labels and fiscal period statement',True);markup=apple.read_text(encoding='utf-8');plain=re.sub(r'\s+',' ',html.unescape(re.sub('<[^>]+>',' ',markup)));assert '2024 and 2022 spanned 52 weeks each' in plain and '2023 spanned 53 weeks' in plain
 tables=[]
 for table in re.findall(r'<table\b[^>]*>(.*?)</table>',markup,re.S|re.I):
  rows=[]
  for row in re.findall(r'<tr\b[^>]*>(.*?)</tr>',table,re.S|re.I):
   cells=[re.sub(r'\s+',' ',html.unescape(re.sub('<[^>]+>',' ',c))).strip() for c in re.findall(r'<t[dh]\b[^>]*>(.*?)</t[dh]>',row,re.S|re.I)]
   if cells:rows.append(cells)
  label=lambda x:re.sub(r'\s*\(\d+\)\s*$','',x)
  if set(categories+['Total net sales'])<={label(r[0]) for r in rows}:tables.append(rows)
 assert tables
 for name in categories+['Total net sales']:
  candidates=[]
  for row in [r for t in tables for r in t]:
   if label(row[0])==name:
    nums=[Q(c.replace(',','')) for c in row[1:] if re.fullmatch(r'\d[\d,]*',c)]
    if len(nums)==3:candidates.append(nums)
  assert candidates and all(v==candidates[0] for v in candidates),name;values[name]=candidates[0]
 source_modes['company']='original_SEC_independent_regex_table_scoped_product_and_service_revenue'
else:
 path=DATA/'actual-ten-Apple-category-fiscal-year-nominal-sales.csv';S=read(path);note(path,'retained actual category net sales; totals reconstructed, not prior summaries');values={name:[Q(next(r['actual_nominal_net_sales_million_USD'] for r in S if int(r['fiscal_year'])==year and r['actual_category']==name)) for year in [2024,2023]] for name in categories};values['Total net sales']=[sum((values[n][i] for n in categories),Q(0)) for i in range(2)];source_modes['company']='retained_actual_ten_category_revenue_cells'
prior=values['Total net sales'][1];current=values['Total net sales'][0];assert prior==383285 and current==391035
sales=[dict(fiscal_year=year,fiscal_weeks=weeks,actual_category=name,actual_nominal_net_sales_million_USD=str(values[name][pos]),is_physical_quantity=False,common_product_price_identified=False) for year,pos,weeks in [(2023,1,53),(2024,0,52)] for name in categories];verify('actual-ten-Apple-category-fiscal-year-nominal-sales.csv',sales)
contributions=[]
for i,name in enumerate(categories):
 old,new=values[name][1],values[name][0];difference=new-old;rate=new/old-1;weight=old/prior;contribution=weight*rate
 contributions.append(dict(actual_category=name,actual_FY2023_sales_million_USD=str(old),actual_FY2024_sales_million_USD=str(new),observed_nominal_difference_million_USD_exact=difference,observed_category_nominal_growth_fraction_exact=rate,FY2023_nominal_sales_weight_exact=weight,nominal_total_growth_contribution_fraction_exact=contribution,is_price_or_volume_causal_effect=False))
 for key,value in [('FY2023Sales',old),('FY2024Sales',new),('difference',difference),('nominalGrowth',rate),('priorRevenueWeight',weight),('growthContribution',contribution)]:add('company_category'+str(i)+'_'+key,value)
verify('derived-five-actual-category-nominal-growth-contributions.csv',contributions);totalgrowth=current/prior-1;unweighted=avg([Q(r['observed_category_nominal_growth_fraction_exact']) for r in contributions]);oldweek=prior/53;newweek=current/52;weekgrowth=newweek/oldweek-1;assert sum((Q(r['nominal_total_growth_contribution_fraction_exact']) for r in contributions),Q(0))==totalgrowth
verify('actual-annual-totals-and-mechanical-week-normalization.csv',[dict(actual_FY2023_total_million_USD=str(prior),actual_FY2024_total_million_USD=str(current),actual_FY2023_weeks=53,actual_FY2024_weeks=52,observed_nominal_annual_growth_fraction_exact=totalgrowth,unweighted_mean_of_five_category_growths_exact=unweighted,mechanical_FY2023_mean_revenue_per_week_million_USD_exact=oldweek,mechanical_FY2024_mean_revenue_per_week_million_USD_exact=newweek,mechanical_per_week_mean_growth_fraction_exact=weekgrowth,weekly_path_is_observed=False,calendar_CPI_is_identified_Apple_output_deflator=False,physical_quantity_growth_identified=False)])
for key,value in dict(FY2023Total=prior,FY2024Total=current,FY2023Weeks=53,FY2024Weeks=52,annualNominalGrowth=totalgrowth,unweightedCategoryGrowth=unweighted,FY2023MechanicalPerWeek=oldweek,FY2024MechanicalPerWeek=newweek,mechanicalPerWeekGrowth=weekgrowth).items():add('company_'+key,value)
CHECKS.update(actualMonthlyRows=588,derivedAnnualMeans=49,sourceRawWagesAvailable=3017,sourceTrimmedLogsAvailable=3010,sourceCategoryRevenueCells=10,CPIUnitConversionIsActual2024Wage=False,annualMeansIndependentlyPublishedByBLS=False,perWeekMeansAreObservedWeeklyPath=False,CPIIsMatchedCompanyOutputDeflator=False)

rpath=ROOT/'econ03-r-results.csv'
if rpath.is_file():
 R={r['metric']:float(r['value']) for r in read(rpath)};assert set(R)==set(METRICS)
 for key,value in METRICS.items():
  near(value,R[key])
  if 0<abs(value)<1e-9:assert abs(R[key]/value-1)<=1e-8,(key,R[key],value)
 CHECKS['RmetricComparisons']=len(METRICS)
else:CHECKS['RmetricComparisons']=0
for item in AUDIT:
 path=ROOT/item['file']
 if not path.is_file():path=WORKSPACE/item['file']
 assert hashlib.sha256(path.read_bytes()).hexdigest()==item['sha256']
CHECKS['inputHashesPreserved']=len(AUDIT)
CHECKS['caseJSONOrPreviousMetricsUsedAsNumericInputs']=False
(ROOT/'econ03-results.json').write_text(json.dumps(dict(chapter='ECON-03',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,sourceModes=source_modes,interpretation='Read original official monthly CPI, anonymous historical raw/log wages and SEC category net sales, with explicit retained-actual-cell fallbacks. Exact arithmetic means retain monthly source rounding and are not independently published annual statistics. The CPI unit conversion is not an observed 2024 wage or individual cost of living. Annual nominal category growth and mechanical week normalization do not identify physical output, matched output deflators, causal effects or weekly sales patterns.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('ECON-03:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
