"""ECON-05: actual economic/wage/accounts anchors and explicitly assumed production/costs.
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/'econ05-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

rawdir=WORKSPACE/'work/textbooks-2026/raw';wb=rawdir/'worldbank-panel.json';note(wb,'actual original World Bank API; level and positional record independently read',True);O=json.loads(wb.read_text(encoding='utf-8'),parse_float=D)[1];matches=[(i,r) for i,r in enumerate(O,1) if r['countryiso3code']=='KOR' and r['date']=='2024' and r['indicator']['id']=='NY.GDP.PCAP.KD'];assert len(matches)==1;pos,source=matches[0];G=Q(source['value']);W=read(COMMON/'worldbank.csv');note(COMMON/'worldbank.csv','retained actual GDPpc level cross-check');r=next(r for r in W if r['country']=='KOR' and r['year']=='2024');same(G,r['gdp_pc']);verify('actual-Korea2024-GDPpc-level-anchor-and-absent-inputs.csv',[dict(source_API_row=pos,country='KOR',source_year=2024,indicator='NY.GDP.PCAP.KD',actual_GDPpc_constant2015USD_source_decimal=G,labor_or_capital_input_observed_here=False,total_GDP_or_TFP_observed_here=False)]);add('source_country_APIrow',pos);add('source_country_GDPpc2024',G)
countryProfiles=[]
for i in range(1,9):
 s=Q(i,4);z=s*s;row=dict(assumed_input_index_exact=z,chosen_exact_square_root_of_index=s,linear_model_output_unit_exact=G*z,root_model_output_unit_exact=G*s,linear_model_marginal_output_per_index_exact=G,root_model_marginal_output_per_index_exact=G/(2*s),actual_output_observed_at_this_input=False,assumed_input_is_actual_labor_hours=False,model_is_empirical_national_production_function=False);countryProfiles.append(row)
 for k,v in row.items():
  if isinstance(v,Q):add('country_query'+str(i-1)+'_'+k,v)
verify('explicit-eight-two-production-proxy-curves-and-slopes.csv',countryProfiles)
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)

apple=WORKSPACE/'work/textbook-rewrite-2026/source-audit-math08/apple-2024.html';note(apple,'actual original consolidated income table independently selected from HTML',True);markup=apple.read_text(encoding='utf-8');required=['Total net sales','Total cost of sales','Total operating expenses','Operating income'];tables=[]
for table in re.findall(r'<table\b[^>]*>(.*?)</table>',markup,re.S|re.I):
 clean=re.sub(r'\s+',' ',html.unescape(re.sub('<[^>]+>',' ',table)))
 if all(label in clean for label in required):tables.append(table)
assert len(tables)==1,len(tables);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 row in re.findall(r'<tr\b[^>]*>(.*?)</tr>',tables[0],re.S|re.I):
  clean=re.sub(r'\s+',' ',html.unescape(re.sub('<[^>]+>',' ',row))).strip()
  if clean.startswith(label):
   clean=re.sub(r'\b\d+(?:\.\d+)?\s*%',' ',clean);numbers=re.findall(r'\b\d[\d,]*\b',clean)
   if len(numbers)==3:hits.append([Q(v.replace(',','')) for v in numbers])
 assert len(hits)==1,(label,hits)
 return hits[0]
accounting={k:financial(k) for k in required};companySource=[]
for i,year,weeks in [(1,2023,53),(0,2024,52)]:
 revenue,cost,opex,inc=[accounting[k][i] for k in required];assert revenue-cost-opex==inc;row=dict(source_fiscal_year=year,source_fiscal_weeks=weeks,actual_revenue_million_USD=revenue,actual_cost_of_sales_million_USD=cost,actual_operating_expenses_million_USD=opex,actual_operating_income_million_USD=inc,accounting_identity_holds=True,physical_output_quantity_observed=False,fixed_variable_or_marginal_cost_identified=False);companySource.append(row)
 for k in ['source_fiscal_weeks','actual_revenue_million_USD','actual_cost_of_sales_million_USD','actual_operating_expenses_million_USD','actual_operating_income_million_USD']:add('source_company_'+str(year)+'_'+k,row[k])
verify('actual-two-Apple-consolidated-operating-income-identities.csv',companySource);revenue,cost,opex,inc=[accounting[k][0] for k in required];C0=cost+opex;personProfiles=[]
for A in [Q(1),Q(2),Q(4)]:
 for q in map(Q,range(9)):
  L=q*q/(A*A);VC=wage*L;TC=10+VC;MC=2*wage*q/(A*A);row=dict(assumed_productivity_output_per_sqrt_hour_exact=A,assumed_output_units_exact=q,conditional_required_labor_hours_exact=L,actual_wage_anchor_1976USD_per_hour_exact=wage,assumed_fixed_cost_1976USD_exact=Q(10),conditional_variable_cost_1976USD_exact=VC,conditional_total_cost_1976USD_exact=TC,conditional_average_total_cost_1976USD_per_output_exact=TC/q if q else None,average_cost_defined=q>0,conditional_marginal_cost_1976USD_per_output_exact=MC,production_or_output_observed=False,additional_paid_labor_available_verified=False,source_person_actual_productivity_identified=False);personProfiles.append(row)
  assert A*A*L==q*q and VC==wage*L
  for k,v in row.items():
   if isinstance(v,Q):add('person_query'+str(len(personProfiles)-1)+'_'+k,v)
verify('explicit27-inverse-production-labor-and-cost-profiles.csv',personProfiles);companyProfiles=[];optima=[];b=Q(100000);lo=Q(1,2);hi=Q(3,2)
for a in [Q(200000),Q(400000)]:
 for q in [lo,Q(1),hi]:
  C=C0+a*(q-1)+b*(q-1)**2;R=revenue*q;pi=R-C;MC=a+2*b*(q-1);row=dict(assumed_cost_slope_at_anchor_million_USD_per_index_exact=a,assumed_curvature_coefficient_million_USD_per_index_squared_exact=b,assumed_activity_index_exact=q,assumed_revenue_million_USD_exact=R,assumed_total_operating_cost_million_USD_exact=C,assumed_operating_profit_million_USD_exact=pi,assumed_marginal_cost_million_USD_per_index_exact=MC,curve_matches_disclosed_anchor_at_index1=True,activity_index_is_observed_product_quantity=False,cost_curve_or_profit_counterfactual_identified=False);companyProfiles.append(row);assert C>0
  for k,v in row.items():
   if isinstance(v,Q):add('company_query'+str(len(companyProfiles)-1)+'_'+k,v)
 un=1+(revenue-a)/(2*b);q=max(lo,min(hi,un));profit=lambda z:revenue*z-C0-a*(z-1)-b*(z-1)**2;derivative=revenue-a-2*b*(q-1);assert profit(q)>=profit(lo) and profit(q)>=profit(hi)
 # Exact concave-quadratic identity proves the maximum throughout the interval.
 for t in [lo,Q(1),hi]:assert profit(t)-profit(q)==derivative*(t-q)-b*(t-q)**2 and profit(t)<=profit(q)
 row=dict(assumed_anchor_cost_slope_exact=a,assumed_lower_activity_bound_exact=lo,assumed_upper_activity_bound_exact=hi,unconstrained_profit_maximizer_exact=un,constrained_profit_maximizer_exact=q,assumed_maximum_profit_million_USD_exact=profit(q),profit_derivative_at_constrained_maximum_exact=derivative,upper_bound_binds=q==hi,model_optimum_is_actual_company_recommendation=False);optima.append(row)
 for k,v in row.items():
  if isinstance(v,Q):add('company_optimum'+str(len(optima)-1)+'_'+k,v)
verify('explicit-six-cost-family-revenue-and-profit-profiles.csv',companyProfiles);verify('explicit-two-constrained-profit-model-maxima.csv',optima)
CHECKS.update(actualGDPpcLevelNotRelabeledTechnology=True,actualWageDoesNotVerifyWorkAvailability=True,actualAccountingIdentityVerified=True,consolidatedTableNotSegmentSelected=True,sourceRawAvailable=3017,sourceLogsAvailable=3010,averageCostUndefinedAtZeroPreserved=True,actualPhysicalProductionOrMarginalCostInferred=False,hypotheticalCostsPositiveOnDeclaredDomain=True,interiorAndBoundaryMaximaChecked=True)

rpath=ROOT/'econ05-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/'econ05-results.json').write_text(json.dumps(dict(chapter='ECON-05',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original World Bank API, Card fixed-width raw wages/logs and uniquely scoped consolidated SEC income table are numeric inputs, not case JSON or previous results. One GDPpc level or accounting total identifies no actual technology, TFP, work opportunity, physical output, MC or fixed-variable cost decomposition. Assumed rational-square input curves, inverse A-sqrt-L production, fixed10 and two cost families preserve distinct units. Undefined average cost at zero remains unavailable. Exact bounded concave-profit optimization distinguishes interior from upper-bound maxima without actual corporate advice.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('ECON-05:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
