"""DATA-15: actual-source reports and explicit decision penalties.
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/'data15-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




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
C=read(COMMON/'college-proximity.csv');note(COMMON/'college-proximity.csv','retained actual people with missingness');archive=raw/'proximity.zip';spec=[('person',1,5),('nearc4',10,10),('education',18,19),('age',24,25),('log_wage',86,97),('metro',116,116),('south',120,120)]
if archive.is_file():
    note(archive,'original Card fixed-width person observations',True)
    with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines()
    assert len(lines)==len(C)==3613;people=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for o,r in zip(people,C):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:people=[{k:Q(r[k]) if r[k] else None for k,a,b in spec} for r in C]
w=[r['log_wage'] for r in people if r['log_wage'] is not None];assert len(w)==3010

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

country=[];auditdir=WORKSPACE/'work/textbook-rewrite-2026/source-audit-data13'
for page in [1,2]:
 name='wb-KOR-GDP2019-2024-page'+str(page)+'.json';path=auditdir/name
 if not path.is_file():path=ROOT/'data13-sources'/('source-'+name)
 note(path,'actual official public response page',True);header,rows=json.loads(path.read_text(encoding='utf-8'),parse_float=D);assert header['page']==page and len(rows)==3
 for r in rows:
  v=Q(r['value']);shown=Q(round(v*1000),1000);country.append(dict(ISO=r['countryiso3code'],year=int(r['date']),indicator_code=r['indicator']['id'],actual_GDPpc_constant2015USD_source_decimal=str(r['value']),chosen_display_rounded3dp_exact=shown,rounding_difference_display_minus_source_exact=shown-v,source_lastupdated=header['lastupdated'],retrievedOn='2026-10-26',unit='constant2015USD/person'))
country.sort(key=lambda r:r['year']);verify('actual-six-GDP-records-and-explicit-display-rounding.csv',country);start=Q(country[0]['actual_GDPpc_constant2015USD_source_decimal']);end=Q(country[-1]['actual_GDPpc_constant2015USD_source_decimal']);origin=Q(33000);heightRatio=(end-origin)/(start-origin)
verify('explicit-axis-origin-illustration-on-actual-GDP-values.csv',[dict(first_year=2019,last_year=2024,actual_first_GDPpc_exact=start,actual_last_GDPpc_exact=end,actual_value_ratio_exact=end/start,actual_value_growth_fraction_exact=end/start-1,explicit_hypothetical_truncated_bar_origin=33000,truncated_height_ratio_exact=heightRatio,height_ratio_is_economic_value_ratio=False,source_values_are_modified=False)])
for r in country:
 for key,v in [('actual',Q(r['actual_GDPpc_constant2015USD_source_decimal'])),('roundedDisplay',r['chosen_display_rounded3dp_exact']),('roundingError',r['rounding_difference_display_minus_source_exact'])]:add('country_'+str(r['year'])+'_'+key,v)
for key,v in dict(actualRatio=end/start,actualGrowth=end/start-1,hypotheticalTruncatedHeightRatio=heightRatio,selectedRecords=len(country)).items():add('country_'+key,v)
groups=[]
for band in ['schooling_le12','schooling_gt12']:
 rs=[o for o in people if (o['education']<=12)==(band=='schooling_le12')];logs=[o['log_wage'] for o in rs if o['log_wage'] is not None];s=sum(logs,Q(0));mu=avg(logs)
 groups.append(dict(education_band=band,source_records=len(rs),available_source_logs=len(logs),unavailable_source_logs=len(rs)-len(logs),available_source_log_sum_exact=s,available_source_log_mean_exact=mu,actual_variable='source_trimmed_log1976_hourly_wage_in_cents',individual_source_codes_in_this_report=False,individual_rows_in_this_report=False,source_aggregation_proves_formal_anonymity=False))
 for key,v in [('sourceRecords',len(rs)),('logAvailable',len(logs)),('logUnavailable',len(rs)-len(logs)),('logSum',s),('logMean',mu)]:add('person_'+band+'_'+key,v)
verify('actual-two-education-band-aggregate-report-with-valid-denominators.csv',groups)
path=DATA/'explicit-aggregate-report-field-release-policy.csv';S=read(path);note(path,'declared report field-release choices checked, not a privacy theorem');assert len(S)==7
expected={k:(a,c) for k,a,c in [('original_person_code',True,False),('individual_source_row_position',True,False),('education_band',False,True),('available_and_unavailable_log_denominators',False,True),('available_group_log_mean',False,True),('source_URL_unit_period_and_SHA256',False,True),('external_identity_linkage',False,False)]}
assert {r['item'] for r in S}==set(expected)
for r in S:assert (r['present_in_published_source'],r['in_this_aggregate_report'])==tuple(str(v) for v in expected[r['item']])
CH=read(COMMON/'churn.csv');note(COMMON/'churn.csv','actual retained anonymous customer observations');path=raw/'churn.zip'
if path.is_file():
 note(path,'original actual3150x14 customer source cells',True)
 with zipfile.ZipFile(path) as z:origin=list(csv.DictReader(io.StringIO(z.read('Customer Churn.csv').decode('utf-8-sig'))))
 assert len(origin)==len(CH)==3150
 for i,(o,r) in enumerate(zip(origin,CH),1):
  same(Q(i),r['row_id'])
  for k,v in o.items():same(Q(v),r[k.strip().lower().replace(' ','_')])
joint=[]
for complaint in [0,1]:
 for outcome in [0,1]:
  n=sum(Q(r['complains'])==complaint and Q(r['churn'])==outcome for r in CH);joint.append(dict(actual_complaint_code=complaint,actual_month12_churn_code=outcome,actual_source_records=n,source_total_records=len(CH)));add('company_cell'+str(complaint)+str(outcome),n)
verify('actual-four-complaint-and-month12-outcome-cells.csv',joint);rules=[]
for i,name in enumerate(['predict_none','complaint_flag','predict_all']):
 tp=fp=fn=tn=0
 for r in CH:
  y=int(Q(r['churn']));pred=0 if name=='predict_none' else 1 if name=='predict_all' else int(Q(r['complains']))
  tp+=pred==1 and y==1;fp+=pred==1 and y==0;fn+=pred==0 and y==1;tn+=pred==0 and y==0
 precision=Q(tp,tp+fp) if tp+fp else None;accuracy=Q(tp+tn,len(CH));recall=Q(tp,tp+fn)
 rules.append(dict(rule=name,source_records=len(CH),TP=tp,FP=fp,FN=fn,TN=tn,observed_accuracy_exact=accuracy,observed_recall_exact=recall,observed_precision_exact=precision,precision_defined=precision is not None,observed_classification_errors=fp+fn,prediction_rule_fit_on_this_source=False,future_validation_performed=False,intervention_prevents_churn_identified=False))
 for key,v in [('TP',tp),('FP',fp),('FN',fn),('TN',tn),('accuracy',accuracy),('recall',recall),('precisionDefined',int(precision is not None)),('errors',fp+fn)]:add('company_rule'+str(i)+'_'+key,v)
 if precision is not None:add('company_rule'+str(i)+'_precision',precision)
verify('actual-retrospective-three-rule-classification-counts.csv',rules);costs=[]
for fpCost,fnCost in [(1,1),(1,20),(20,1)]:
 for r in rules:
  penalty=fpCost*r['FP']+fnCost*r['FN'];costs.append(dict(rule=r['rule'],assumed_false_positive_penalty=fpCost,assumed_false_negative_penalty=fnCost,calculated_label_error_penalty=penalty,actual_source_FP=r['FP'],actual_source_FN=r['FN'],penalty_unit='explicitly_assumed_score_not_observed_currency',financial_or_intervention_benefit_estimated=False));add('company_assumedPenalty_'+str(fpCost)+'_'+str(fnCost)+'_'+r['rule'],penalty)
verify('explicit-nine-assumed-label-error-penalty-comparisons.csv',costs)
CHECKS.update(actualCountryRecords=6,originalPeopleRows=len(people),availableSourceLogs=len(w),actualCustomerRecords=len(CH),actualCustomerChurns=sum(Q(r['churn'])==1 for r in CH),retrospectiveRules=3,assumedPenaltyScenarios=9,undefinedNoPositivePrecisionPreserved=True,individualRowsNotReexportedInThisAggregateReport=True,identityLinkagePerformed=False,actualFutureValidationPerformed=False,actualInterventionBenefitEstimated=False)

rpath=ROOT/'data15-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/'data15-results.json').write_text(json.dumps(dict(chapter='DATA-15',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original actual public observations are numeric inputs, not case JSON or previous results. Display rounding and truncated bar-origin examples are explicit choices. A two-band aggregate release is not a formal privacy guarantee; no external personal linkage is performed. Retrospective fixed-rule classification counts and assumed FP/FN penalty scores do not validate future predictions, causal retention benefits or currency savings. Browser and assistive-technology accessibility QA is separate from this numeric reproduction.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-15:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
