"""ECON-02: 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/'econ02-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 field(line,a,b):
    s=line[a-1:b].strip();return None if s in ['','.'] else Q(s)
raw=WORKSPACE/'work/textbooks-2026/raw';W=read(COMMON/'worldbank.csv');note(COMMON/'worldbank.csv','actual retained country-year observations');originalfile=raw/'worldbank-panel.json'
if originalfile.is_file():
    note(originalfile,'original World Bank API response',True);original=json.loads(originalfile.read_text(encoding='utf-8'),parse_float=D)[1];lookup={(r['countryiso3code'],r['date'],r['indicator']['id']):r['value'] for r in original};assert len(original)==6480
    for r in W:
        for key,code in [('gdp_pc','NY.GDP.PCAP.KD'),('life_expectancy','SP.DYN.LE00.IN')]:
            v=lookup[(r['country'],r['year'],code)]
            if v is None:assert r[key]==''
            else:same(Q(v),r[key])
countries=sorted([r for r in W if r['year']=='2024'],key=lambda r:r['country']);assert len(countries)==16

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

# Read actual observations; neither case JSON nor a previous result is an input.
source_modes={};positions={(r['countryiso3code'],r['date'],r['indicator']['id']):i for i,r in enumerate(original,1)} if originalfile.is_file() else {}
G=sorted([r for r in W if r['country']=='KOR' and 2014<=int(r['year'])<=2024],key=lambda r:int(r['year']));assert len(G)==11
decimal=lambda x:D(x.numerator)/D(x.denominator)
base=Q(G[0]['gdp_pc']);end=Q(G[-1]['gdp_pc']);a=(end-base)/10;k=(decimal(end)/decimal(base)).ln()/10
S=read(DATA/'actual11-Korea-GDP-and-explicit-two-anchor-models.csv');note(DATA/'actual11-Korea-GDP-and-explicit-two-anchor-models.csv','actual eleven annual values and independently reconstructed chosen paths');assert len(S)==11
for r,o in zip(G,S):
 year=int(r['year']);t=year-2014;linear=base+a*t;exp=decimal(base) if t==0 else decimal(end) if t==10 else decimal(base)*(k*t).exp();slope=k*exp
 same(Q(year),o['year']);same(Q(r['gdp_pc']),o['actual_GDPpc_constant2015USD_source_decimal']);same(linear,o['chosen_two_anchor_linear_exact']);same(a,o['linear_slope_USD_per_person_per_year_exact'])
 if positions:same(Q(positions[('KOR',r['year'],'NY.GDP.PCAP.KD')]),o['source_API_row'])
 for key,v in [('chosen_two_anchor_exponential_Decimal80_approx',exp),('exponential_slope_USD_per_person_per_year_Decimal80_approx',slope)]:assert abs(D(o[key])-v)<=D('1e-65')*max(D(1),abs(v))
 assert o['model_values_are_actual_annual_observations']=='False'
 for key,value in [('actualGDPpc',Q(r['gdp_pc'])),('linear',linear),('exponential',exp),('exponentialSlope',slope),('linearMinusActual',linear-Q(r['gdp_pc'])),('exponentialMinusActual',exp-D(r['gdp_pc']))]:add('country_'+str(year)+'_'+key,value)
add('country_linear_slope',a);add('country_exponential_continuous_rate',k);source_modes['country']='original_API_response' if originalfile.is_file() else 'retained_actual_common_country_year_observations'
archive=raw/'proximity.zip'
if archive.is_file():
 note(archive,'actual anonymous source raw cents/hour and separately source-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 '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_fixed_width_archive'
else:
 path=ROOT/'econ01-sources/actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv';C=read(path);note(path,'actual complete raw/log source observations retained in ECON01; original archive unavailable');people=[dict(row=int(r['source_row_id']),code=Q(r['source_person_code']),raw=Q(r['actual1976_raw_hourly_wage_cents']) if r['actual1976_raw_hourly_wage_cents'] else None,log=Q(r['actual1976_source_trimmed_log_hourly_wage_cents']) if r['actual1976_source_trimmed_log_hourly_wage_cents'] else None) for r in C];source_modes['person']='retained_actual_complete_ECON01_raw_log_observations'
first=people[0];w=first['raw']/100;assert first['row']==1 and first['code']==2 and first['raw']==548
verify('actual-anonymous-wage-anchor-and-explicit-assumption-flags.csv',[dict(source_row_id=1,original_person_code='2',actual1976_raw_hourly_wage_cents_source_decimal='548',actual1976_raw_hourly_wage_USD_exact=w,chosen_daily_time_budget_hours='24',time_budget_and_preference_are_observed=False,additional_paid_work_offered_by_source=False)])
for key,value in dict(records=len(people),rawAvailable=sum(r['raw'] is not None for r in people),logAvailable=sum(r['log'] is not None for r in people),rawUnavailable=sum(r['raw'] is None for r in people),logUnavailable=sum(r['log'] is None for r in people),rawAvailableLogUnavailable=sum(r['raw'] is not None and r['log'] is None for r in people),firstRawCents=first['raw'],firstHourly1976USD=w).items():add('person_'+key,value)
scenarios=[]
for v in map(Q,[0,8,12,20]):
 for gamma in [Q(1,2),Q(1)]:
  for wage in [w,w+1]:
   l=max(Q(0),min(Q(24),(v-wage)/gamma));h=24-l;cash=wage*h;utility=cash+v*l-gamma*l*l/2
   row=dict(assumed_leisure_initial_value_USDequiv_per_hour_exact=v,assumed_gamma_USDequiv_per_hour_squared_exact=gamma,hourly_wage_1976USD_exact=wage,wage_is_actual_source_anchor=wage==w,chosen_daily_time_budget_hours=24,chosen_optimal_leisure_hours_exact=l,chosen_work_hours_exact=h,conditional_gross_cash1976USD_exact=cash,hypothetical_utility_USDequiv_exact=utility,choice_and_preferences_are_actual_observations=False,extra_work_availability_is_assumed=True);scenarios.append(row)
   for key,value in [('v',v),('gamma',gamma),('wage',wage),('leisure',l),('work',h),('cash',cash),('utility',utility)]:add('person_scenario'+str(len(scenarios)-1)+'_'+key,value)
   # Strict concavity: endpoint/interior choice beats every integer-hour alternative.
   for trial in range(25):assert utility>=wage*(24-trial)+v*trial-gamma*trial*trial/2
verify('explicit-hypothetical-quasilinear-time-choice-profiles.csv',scenarios)
APPLE=WORKSPACE/'work/textbook-rewrite-2026/source-audit-math08/apple-2024.html'
if APPLE.is_file():
 note(APPLE,'original SEC total net sales 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
 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.startswith('Total net sales'):
   values=re.findall(r'\b\d[\d,]*\b',clean)
   if len(values)==3:candidates.append([Q(v.replace(',','')) for v in values])
 assert candidates and all(row==candidates[0] for row in candidates);revenue=candidates[0][0];assert revenue==391035;source_modes['company']='actual_original_SEC_HTML_independent_regex_table_rows'
else:
 path=DATA/'actual-Apple-total-annual-net-sales-anchor.csv';T=read(path);note(path,'actual annual reported total retained; original HTML unavailable');revenue=Q(T[0]['actual_total_net_sales_million_USD_source_decimal']);source_modes['company']='retained_actual_annual_total_observation'
verify('actual-Apple-total-annual-net-sales-anchor.csv',[dict(source_fiscal_year=2024,source_fiscal_weeks=52,actual_total_net_sales_million_USD_source_decimal=revenue,actual_unit_price_and_volume_identified=False)])
add('company_actual_revenue_millionUSD',revenue);add('company_actual_fiscal_weeks',52)
decompositions=[]
for price in map(Q,[500,1000,1500]):
 q=revenue/price;decompositions.append(dict(actual_revenue_anchor_million_USD=revenue,assumed_composite_unit_price_USD_exact=price,implied_composite_quantity_million_units_exact=q,price_or_quantity_actually_reported=False,composite_unit_is_actual_individual_product=False));add('company_decomposition'+str(len(decompositions)-1)+'_price',price);add('company_decomposition'+str(len(decompositions)-1)+'_quantity',q);assert price*q==revenue
verify('explicit-nonidentified-price-volume-decompositions.csv',decompositions);p0=Q(1000);q0=revenue/p0;profiles=[]
for slope in [Q(1),Q(4)]:
 for delta in [Q(-10),Q(0),Q(10)]:
  q=q0+delta;p=p0-slope*delta;rev=p*q;mr=p-slope*q
  profiles.append(dict(assumed_inverse_demand_slope_USD_per_million_units_exact=slope,assumed_composite_quantity_million_units_exact=q,assumed_composite_unit_price_USD_exact=p,assumed_model_revenue_million_USD_exact=rev,assumed_revenue_slope_USD_per_unit_exact=mr,actual_disclosed_revenue_anchor_million_USD=revenue,model_price_volume_demand_or_marginal_revenue_identified_from_source=False))
  for key,value in [('b',slope),('q',q),('p',p),('revenue',rev),('marginalRevenue',mr)]:add('company_profile'+str(len(profiles)-1)+'_'+key,value)
verify('explicit-two-demand-slope-revenue-model-profiles.csv',profiles)
CHECKS.update(actualAnnualGDPObservations=11,sourceRawWagesAvailable=3017,sourceLogsAvailable=3010,hypotheticalChoiceProfiles=len(scenarios),integerHourUtilityComparisons=16*25,actualCompositePriceVolumeIdentified=False,hypotheticalDemandProfiles=len(profiles),sameRevenueDoesNotIdentifyMarginalRevenue=True,actualSourceDataUnchanged=True)

rpath=ROOT/'econ02-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/'econ02-results.json').write_text(json.dumps(dict(chapter='ECON-02',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,sourceModes=source_modes,interpretation='Read original public annual GDP, anonymous 1976 raw wages and SEC aggregate annual sales, with explicit retained-actual-observation fallbacks. Neither case JSON nor previous results supplies numeric inputs. Two-anchor interpolation uses the future endpoint retrospectively, not a 2014-issued forecast. Time budget/preferences/extra hours and composite price/quantity/demand are assumed. Model slopes are not identified empirical causal effects, actual observed choices, profit or welfare.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('ECON-02:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
