"""ECON-01: 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/'econ01-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,platform

raw=WORKSPACE/'work/textbooks-2026/raw';source_modes={}
def avg(v):return sum(v,Q(0))/len(v)
def verify(name,expected):
 path=DATA/name;S=read(path);note(path,'all source cells or explicitly hypothetical arithmetic independently reconstructed');assert len(S)==len(expected),(name,len(S),len(expected))
 for o,r in zip(expected,S):
  assert set(o)==set(r),(name,set(o),set(r))
  for k,value in o.items():
   if isinstance(value,bool):assert r[k]==str(value)
   elif value is None:assert r[k]==''
   elif isinstance(value,(Q,int)):same(Q(value),r[k])
   else:assert r[k]==str(value),(name,k,r[k],value)
 return S
PDF=WORKSPACE/'work/textbook-rewrite-2026/source-audit-econ01/MOEF-2025-original-budget-enacted-2024-12-10.pdf'
if PDF.is_file():
 note(PDF,'actual government original-budget PDF; historical enactment not outturn',True);proc=subprocess.run(['pdftotext','-layout',str(PDF),'-'],capture_output=True,text=True,encoding='utf-8',check=True);pages=proc.stdout.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 label,token in [('R_and_D','R&D'),('culture_sports_tourism','문화')]:
  line=next(l for l in pages[2].splitlines() if token in l);sectors[label]=list(map(Q,re.findall(r'\d[\d,]*\.\d+',line)[:3]))
 source_modes['budget']='actual_original_PDF_via_pdftotext'
else:
 path=DATA/'actual-MOEF-original-budget-levels-as-published.csv';S=read(path);note(path,'retained actual published budget values; original PDF unavailable');levels=[Q(r['reported_total_expenditure_trillion_KRW']) for r in S];S=read(DATA/'actual-MOEF-two-sector-reference-levels-as-published.csv');sectors={label:[Q(r['reported_sector_trillion_KRW']) for r in S if r['sector']==label] for label in ['R_and_D','culture_sports_tourism']};source_modes['budget']='retained_actual_published_CSV_original_PDF_unavailable'
budget=[dict(source_year=year,budget_status=status,reported_total_expenditure_trillion_KRW=level,source_publication_date='2024-12-10',source_pdf_page=1,actual_outturn=False) for (year,status),level in zip([(2024,'enacted_original'),(2025,'proposal'),(2025,'enacted_original')],levels)];verify('actual-MOEF-original-budget-levels-as-published.csv',budget)
sectorrows=[]
for label,values in sectors.items():
 for (year,status),value in zip([(2024,'enacted_original'),(2025,'proposal'),(2025,'enacted_original')],values):sectorrows.append(dict(sector=label,source_year=year,budget_status=status,reported_sector_trillion_KRW=value,source_pdf_page=3,source_publication_date='2024-12-10',actual_outturn=False))
verify('actual-MOEF-two-sector-reference-levels-as-published.csv',sectorrows);rd=sectors['R_and_D'][2];culture=sectors['culture_sports_tourism'][2];assert (rd,culture)==(Q('29.6'),Q('8.8'))
for key,value in [('2024_original',levels[0]),('2025_proposal',levels[1]),('2025_original',levels[2]),('reported_rounded_level_difference',levels[2]-levels[1]),('2025_RD_reference',rd),('2025_culture_reference',culture),('chosen_two_item_envelope',rd+culture)]:add('country_'+key,value)
countryprofile=[]
for i in range(-10,11):
 delta=Q(i,2);row=dict(chosen_reallocation_to_RD_trillion_exact=delta,hypothetical_RD_trillion_exact=rd+delta,hypothetical_culture_trillion_exact=culture-delta,chosen_fixed_two_item_envelope_exact=rd+culture,is_actual_policy_observation=False,legal_transfer_feasibility_established=False);countryprofile.append(row)
 for key in ['chosen_reallocation_to_RD_trillion_exact','hypothetical_RD_trillion_exact','hypothetical_culture_trillion_exact']:add('country_transfer'+str(i+10)+'_'+key,row[key])
 assert row['hypothetical_RD_trillion_exact']+row['hypothetical_culture_trillion_exact']==rd+culture
verify('explicit-hypothetical-fixed-two-item-reallocation.csv',countryprofile)
archive=raw/'proximity.zip';people=[]
if archive.is_file():
 note(archive,'actual Card fixed-width raw cents/hour and separately trimmed logs',True)
 with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines();book=z.read('code_bk.txt').decode('ascii')
 assert re.search(r'128\s*-\s*132\s+wage76',book) and 'raw wage cents per hour 1976' in book
 def field(line,a,c):
  s=line[a-1:c].strip();return None if s in ['', '.'] else Q(s)
 for i,line in enumerate(lines,1):
  code=field(line,1,5);wage=field(line,128,132);log=field(line,86,97);people.append(dict(source_row_id=i,source_person_code=str(int(code)),actual1976_raw_hourly_wage_cents=wage,actual1976_source_trimmed_log_hourly_wage_cents=log,raw_wage_available=wage is not None,source_trimmed_log_available=log is not None))
 source_modes['person']='actual_original_fixed_width_archive'
else:
 path=DATA/'actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv';S=read(path);note(path,'retained actual raw wage/log records; original archive unavailable')
 for r in S:people.append(dict(source_row_id=int(r['source_row_id']),source_person_code=r['source_person_code'],actual1976_raw_hourly_wage_cents=Q(r['actual1976_raw_hourly_wage_cents']) if r['actual1976_raw_hourly_wage_cents'] else None,actual1976_source_trimmed_log_hourly_wage_cents=Q(r['actual1976_source_trimmed_log_hourly_wage_cents']) if r['actual1976_source_trimmed_log_hourly_wage_cents'] else None,raw_wage_available=r['raw_wage_available']=='True',source_trimmed_log_available=r['source_trimmed_log_available']=='True'))
 source_modes['person']='retained_actual_CSV_original_archive_unavailable'
verify('actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv',people);wages=[r['actual1976_raw_hourly_wage_cents'] for r in people if r['raw_wage_available']];logs=[r['actual1976_source_trimmed_log_hourly_wage_cents'] for r in people if r['source_trimmed_log_available']];rawids={r['source_row_id'] for r in people if r['raw_wage_available']};logids={r['source_row_id'] for r in people if r['source_trimmed_log_available']};assert logids<=rawids;first=people[0];hourly=first['actual1976_raw_hourly_wage_cents']/100
for key,value in dict(all_records=len(people),available_raw_wages=len(wages),unavailable_raw_wages=len(people)-len(wages),available_source_logs=len(logs),unavailable_source_logs=len(people)-len(logs),raw_available_log_unavailable=len(rawids-logids),first_source_row=first['source_row_id'],first_original_person_code=Q(first['source_person_code']),first_hourly_raw_cents=first['actual1976_raw_hourly_wage_cents'],first_hourly1976_USD=hourly,raw_wage_cents_sum=sum(wages,Q(0)),raw_wage_cents_mean=avg(wages),raw_wage_cents_min=min(wages),raw_wage_cents_max=max(wages)).items():add('person_'+key,value)
personprofile=[]
for i in range(17):
 h=Q(i,2);earnings=h*hourly;personprofile.append(dict(chosen_forgone_work_hours_exact=h,scenario_hourly_wage_1976_USD_exact=hourly,conditional_gross_forgone_earnings_1976_USD_exact=earnings,extra_paid_hours_availability_is_assumed=True,observed_additional_hours_offered=False,taxes_or_work_costs_included=False,is_actual_person_decision=False));add('person_scenario'+str(i)+'_assumed_hours',h);add('person_scenario'+str(i)+'_conditional_gross1976_USD',earnings)
verify('explicit-assumed-extra-hours-and-conditional-gross-earnings.csv',personprofile)
APPLE=WORKSPACE/'work/textbook-rewrite-2026/source-audit-math08/apple-2024.html'
if APPLE.is_file():
 note(APPLE,'actual original SEC annual operating-expense table cells and 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
 def financial(label):
  candidates=[]
  for row in re.findall(r'<tr\b[^>]*>(.*?)</tr>',markup,re.S|re.I):
   clean=re.sub(r'\s+',' ',html.unescape(re.sub('<[^>]+>',' ',row))).strip()
   if clean.lower().startswith(label.lower()) and re.match(r'^\s*(?:\$|\d|\()',clean[len(label):]):
    clean=re.sub(r'\b\d+(?:\.\d+)?\s*%',' ',clean);numbers=re.findall(r'\b\d[\d,]*\b',clean)
    if len(numbers)==3:candidates.append([Q(v.replace(',','')) for v in numbers])
  assert candidates and all(r==candidates[0] for r in candidates),(label,candidates)
  return candidates[0]
 rdvalues=financial('Research and development');sgavalues=financial('Selling, general and administrative');totals=financial('Total operating expenses');company=[dict(source_fiscal_year=year,source_fiscal_weeks=weeks,research_and_development_million_USD=rdvalues[index],selling_general_administrative_million_USD=sgavalues[index],total_operating_expenses_million_USD=totals[index],is_marginal_cost_per_extra_product=False) for index,year,weeks in [(1,2023,53),(0,2024,52)]];source_modes['company']='actual_original_SEC_HTML_independent_regex_table_rows'
else:
 S=read(DATA/'actual-Apple-annual-operating-expenses-and-period-weeks.csv');company=[]
 for r in S:company.append({k:(False if k=='is_marginal_cost_per_extra_product' else Q(v)) for k,v in r.items()})
 source_modes['company']='retained_actual_annual_expense_CSV_original_HTML_unavailable'
verify('actual-Apple-annual-operating-expenses-and-period-weeks.csv',company)
for row in company:
 assert row['research_and_development_million_USD']+row['selling_general_administrative_million_USD']==row['total_operating_expenses_million_USD']
 for key in ['source_fiscal_weeks','research_and_development_million_USD','selling_general_administrative_million_USD','total_operating_expenses_million_USD']:add('company_FY'+str(int(row['source_fiscal_year']))+'_'+key,row[key])
add('company_annual_RD_reported_difference_million',company[1]['research_and_development_million_USD']-company[0]['research_and_development_million_USD'])
future=[]
for benefit in range(0,201,25):
 for sunk in [Q(0),Q(1000)]:
  cost=Q(100);cont=Q(benefit)-cost-sunk;stop=-sunk;diff=cont-stop;assert diff==benefit-cost;row=dict(assumed_future_benefit_million_USD_exact=Q(benefit),assumed_avoidable_future_cost_million_USD_exact=cost,assumed_common_irrecoverable_past_cost_million_USD_exact=sunk,assumed_continue_net_including_common_past_exact=cont,assumed_stop_net_including_common_past_exact=stop,incremental_continue_minus_stop_exact=diff,chosen_decision='continue' if diff>0 else 'stop' if diff<0 else 'tie',is_actual_Apple_project_or_forecast=False,discounting_tax_uncertainty_omitted=True);future.append(row)
  for key in ['assumed_future_benefit_million_USD_exact','assumed_avoidable_future_cost_million_USD_exact','assumed_common_irrecoverable_past_cost_million_USD_exact','assumed_continue_net_including_common_past_exact','assumed_stop_net_including_common_past_exact','incremental_continue_minus_stop_exact']:add('company_scenario'+str(len(future)-1)+'_'+key,row[key])
verify('explicit-hypothetical-project-increments-and-common-past-costs.csv',future)
CHECKS.update(caseJSONNotUsedAsNumericInput=True,actualBudgetNotOutturn=True,rawAndTrimmedLogDenominatorsDistinct=True,extraWorkAvailabilityExplicitAssumption=True,annualAccountingExpenseNotAutomaticSunkOrMarginalCost=True,scenarioDifferencesIndependentOfCommonSunkCost=True)

rpath=ROOT/'econ01-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/'econ01-results.json').write_text(json.dumps(dict(chapter='ECON-01',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,sourceModes=source_modes,interpretation='Independent actual government PDF, Card fixed-width raw wages/logs and SEC HTML are numeric inputs with explicit retained-observation fallbacks. Historical original budgets are not outturn or later appropriations. Different raw/trimmed-log availability is preserved. Forgone earnings require an assumed available extra-work opportunity and use gross1976 dollars. Annual accounting expenses differ from causal marginal costs and project sunk costs. Hypothetical transfers and future projects do not identify actual welfare, legal feasibility or corporate choices.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('ECON-01:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
