"""ECON-04: actual budget/wage/expenses and explicitly assumed consumer-choice constraints.
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/'econ04-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 subprocess,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

rawdir=WORKSPACE/'work/textbooks-2026/raw';PDF=WORKSPACE/'work/textbook-rewrite-2026/source-audit-econ01/MOEF-2025-original-budget-enacted-2024-12-10.pdf';note(PDF,'original government budget PDF, not current outturn; independent extraction',True);text=subprocess.run(['pdftotext','-layout',str(PDF),'-'],capture_output=True,text=True,encoding='utf-8',check=True).stdout;pages=text.split('\f');assert '2024.12.10' in pages[0];line=next(l for l in pages[0].splitlines() if '총지출(증가율)' in l);nums=re.findall(r'\d[\d,]*\.\d+',line);levels=[Q(nums[i]) for i in [0,1,3]];sectors={}
for key,token in [('R_and_D','R&D'),('culture_sports_tourism','문화')]:sectors[key]=list(map(Q,re.findall(r'\d[\d,]*\.\d+',next(l for l in pages[2].splitlines() if token in l))[:3]))
government=[]
for category,vs,page in [('total_expenditure',levels,1)]+[(key,v,3) for key,v in sectors.items()]:
 for (year,status),v in zip([(2024,'enacted_original'),(2025,'proposal'),(2025,'enacted_original')],vs):
  government.append(dict(category=category,source_year=year,budget_status=status,reported_trillion_KRW=v,source_pdf_page=page,source_publication_date='2024-12-10',actual_outturn=False));add('source_government_'+category+'_'+str(year)+'_'+status,v)
verify('actual-nine-government-budget-total-and-two-sector-references.csv',government);rd,culture=sectors['R_and_D'][2],sectors['culture_sports_tourism'][2];M=rd+culture
archive=rawdir/'proximity.zip';note(archive,'actual fixed-width raw wage76 and separate source-trimmed log',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
def field(line,a,b):
 s=line[a-1:b].strip();return None if s in ['','.'] else Q(s)
people=[]
for i,line in enumerate(lines,1):
 code=field(line,1,5);w=field(line,128,132);l=field(line,86,97);people.append(dict(source_row_id=i,source_person_code=str(int(code)),actual1976_raw_hourly_wage_cents=w,actual1976_source_trimmed_log_hourly_wage_cents=l,raw_wage_available=w is not None,source_trimmed_log_available=l is not None))
verify('actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv',people);wage=people[0]['actual1976_raw_hourly_wage_cents']/100;pv=dict(rows=len(people),rawAvailable=sum(r['raw_wage_available'] for r in people),logAvailable=sum(r['source_trimmed_log_available'] for r in people),rawWithoutLog=sum(r['raw_wage_available'] and not r['source_trimmed_log_available'] for r in people),firstCode=Q(people[0]['source_person_code']),firstRawCents=people[0]['actual1976_raw_hourly_wage_cents'],firstHourlyUSD=wage)
for k,v in pv.items():add('source_person_'+k,v)
# Parse exact original HTML table cells, independently of the author regex reader.
class Rows(HTMLParser):
 def __init__(self):super().__init__();self.rows=[];self.row=None;self.cell=None
 def handle_starttag(self,t,a):
  if t=='tr':self.row=[]
  if t in ['td','th'] and self.row is not None:self.cell=[]
 def handle_data(self,t):
  if self.cell is not None:self.cell.append(t)
 def handle_endtag(self,t):
  if t in ['td','th'] and self.cell is not None:self.row.append(re.sub(r'\s+',' ',' '.join(self.cell)).strip());self.cell=None
  if t=='tr' and self.row is not None:self.rows.append(self.row);self.row=None
apple=WORKSPACE/'work/textbook-rewrite-2026/source-audit-math08/apple-2024.html';note(apple,'actual original operating-expense table and week statement read with HTMLParser',True);markup=apple.read_text(encoding='utf-8');parser=Rows();parser.feed(markup);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
def financial(label):
 hits=[]
 for cells in parser.rows:
  if cells and cells[0].strip().lower()==label.lower():
   nums=[]
   for j,c in enumerate(cells[1:],1):
    s=c.strip().replace(',','')
    if re.fullmatch(r'\d+',s) and not (j+1<len(cells) and cells[j+1].strip()=='%'):nums.append(Q(s))
   if len(nums)==3:hits.append(nums)
 assert hits and all(r==hits[0] for r in hits),(label,hits)
 return hits[0]
R=financial('Research and development');S=financial('Selling, general and administrative');E=financial('Total operating expenses');company=[dict(source_fiscal_year=year,source_fiscal_weeks=weeks,actual_RD_million_USD=R[i],actual_SGA_million_USD=S[i],actual_operating_expenses_million_USD=E[i],is_actual_household_consumption=False,physical_input_units_available=False) for i,year,weeks in [(1,2023,53),(0,2024,52)]];verify('actual-two-Apple-operating-expense-references.csv',company)
for r in company:
 assert r['actual_RD_million_USD']+r['actual_SGA_million_USD']==r['actual_operating_expenses_million_USD']
 for k in ['source_fiscal_weeks','actual_RD_million_USD','actual_SGA_million_USD','actual_operating_expenses_million_USD']:add('source_company_'+str(r['source_fiscal_year'])+'_'+k,r[k])
countryChoices=[]
for i,a in enumerate([Q(0),Q(1,4),Q(1,2),Q(3,4),rd/M,Q(1)]):
 x=a*M;y=M-x;row=dict(assumed_Cobb_RD_share_exact=a,assumed_two_item_budget_trillion_KRW_exact=M,hypothetical_RD_choice_trillion_KRW_exact=x,hypothetical_culture_choice_trillion_KRW_exact=y,difference_from_reported_RD_trillion_exact=x-rd,difference_from_reported_culture_trillion_exact=y-culture,original_reported_bundle_is_model_optimum=a==rd/M,weights_estimated_from_data=False,legal_transfer_feasibility_established=False,actual_welfare_gain_identified=False);countryChoices.append(row)
 assert x+y==M and x>=0 and y>=0
 for k,v in row.items():
  if isinstance(v,Q):add('country_scenario'+str(i)+'_'+k,v)
verify('explicit-six-country-Cobb-share-choices.csv',countryChoices);reference=[]
for i,(name,kind,unique) in enumerate([('Cobb_share37over48','reported_bundle',True),('Leontief_ratio37to11','reported_bundle',True),('linear_equal_weights','entire_frontier',False),('constant_utility','entire_budget_triangle',False)]):
 reference.append(dict(explicit_hypothetical_preference=name,actual_reference_RD_trillion_exact=rd,actual_reference_culture_trillion_exact=culture,assumed_envelope_trillion_exact=M,reported_bundle_is_one_model_optimum=True,model_optimum_set=kind,model_optimum_is_unique=unique,preference_identified_by_budget_data=False,actual_government_optimality_established=False));add('country_compatiblePreference'+str(i)+'_unique',int(unique))
assert rd/M==Q(37,48) and rd/culture==Q(37,11);verify('explicit-four-preferences-compatible-with-reported-country-bundle.csv',reference)
personChoices=[]
for v in [Q(0),Q(40),Q(200)]:
 for a in [Q(1,4),Q(1,2),Q(3,4)]:
  T=Q(24);wealth=v+wage*T;uncapped=(1-a)*wealth/wage
  # Independently compare the positive concave log objective's peak with [0,T].
  ell=uncapped if uncapped<T else T;h=T-ell;c=v+wage*h;assert c+wage*ell==wealth and 0<=ell<=T and h>=0
  if ell<T:assert a*wage*ell==(1-a)*c
  else:assert (1-a)/ell-a*wage/c>=0
  row=dict(assumed_Cobb_consumption_share_exact=a,assumed_time_endowment_hours_exact=T,assumed_nonlabor_income_1976_USD_exact=v,observed_hourly_wage_1976_USD_exact=wage,assumed_full_income_1976_USD_exact=wealth,unconstrained_Cobb_leisure_hours_exact=uncapped,hypothetical_leisure_hours_exact=ell,hypothetical_work_hours_exact=h,hypothetical_consumption_1976_USD_exact=c,time_upper_bound_binds=ell==T,extra_paid_hours_available_is_assumption=True,observed_actual_leisure_or_consumption=False,actual_labor_supply_elasticity_identified=False);personChoices.append(row)
  for k,value in row.items():
   if isinstance(value,Q):add('person_scenario'+str(len(personChoices)-1)+'_'+k,value)
verify('explicit-nine-person-time-budget-Cobb-choices.csv',personChoices);companyChoices=[]
for i,a in enumerate([Q(1,4),Q(1,2),Q(3,4),R[0]/E[0]]):
 x=a*E[0];y=E[0]-x;row=dict(assumed_Cobb_RD_share_exact=a,assumed_fixed_expense_envelope_million_USD_exact=E[0],hypothetical_RD_choice_million_USD_exact=x,hypothetical_SGA_choice_million_USD_exact=y,difference_from_reported_RD_million_USD_exact=x-R[0],difference_from_reported_SGA_million_USD_exact=y-S[0],reported_bundle_is_model_optimum=a==R[0]/E[0],weights_estimated_from_data=False,actual_liquid_transfer_feasibility_established=False,actual_productivity_gain_identified=False);companyChoices.append(row)
 for k,v in row.items():
  if isinstance(v,Q):add('company_scenario'+str(i)+'_'+k,v)
verify('explicit-four-company-Cobb-share-choices.csv',companyChoices);ordinal=[]
for i,(x,y) in enumerate([(Q(1),Q(4)),(Q(2),Q(3)),(Q(3),Q(2)),(Q(4),Q(1))]):
 u=x*y;row=dict(assumed_bundle_x_exact=x,assumed_bundle_y_exact=y,chosen_utility_xy_exact=u,strict_increasing_square_transform_on_nonnegative_values_exact=u*u,values_are_measured_happiness=False,ranking_preserved=True);ordinal.append(row)
 for k,v in row.items():
  if isinstance(v,Q):add('ordinal_bundle'+str(i)+'_'+k,v)
verify('explicit-four-ordinal-ranking-bundles.csv',ordinal)
for a in ordinal:
 for c in ordinal:assert (a['chosen_utility_xy_exact']>c['chosen_utility_xy_exact'])==(a['strict_increasing_square_transform_on_nonnegative_values_exact']>c['strict_increasing_square_transform_on_nonnegative_values_exact'])
CHECKS.update(originalBudgetPDFUsed=True,originalFixedWidthRawWagesUsed=True,originalSECHTMLUsed=True,actualGovernmentOutturnClaimed=False,actualHouseholdObservationForGovernmentCompanyClaimed=False,actualPreferencesIdentified=False,actualTransfersOrWelfareIdentified=False,actualPersonBehaviorInferred=False,personTimeCapBindings=sum(r['time_upper_bound_binds'] for r in personChoices),ordinalRankingsPreserved=True)

rpath=ROOT/'econ04-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/'econ04-results.json').write_text(json.dumps(dict(chapter='ECON-04',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original actual MOEF PDF, Card fixed-width wage/log archive and SEC expense tables, not case JSON or previous results, are numeric inputs. Monetary envelopes, one-for-one transfers, Cobb weights,24-hour opportunity and nonlabor income are separate assumptions. Preserve actual units/years, raw3017 versus source-log3010 denominators and52/53-week fiscal lengths. Compatible preference sets do not identify actual preferences or welfare. Person solutions enforce the time cap and ordinal utility transformations preserve rankings without measuring happiness.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('ECON-04:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
