"""DATA-14: actual-source contracts and expected rule rejections.
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/'data14-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 unittest,sys,platform

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
NJ=read(COMMON/'nj-minwage.csv');note(COMMON/'nj-minwage.csv','actual stores retaining both waves and missingness');archive=raw/'njmin.zip';spec=[('store',1,3),('chain',5,5),('nj',9,9),('ft_before',26,30),('pt_before',32,36),('managers_before',38,42),('wage_before',44,48),('status_after',110,110),('ft_after',122,126),('pt_after',128,132),('managers_after',134,138),('wage_after',140,144)]
if archive.is_file():
    note(archive,'original Card/Krueger fixed-width store observations',True)
    with zipfile.ZipFile(archive) as z:lines=z.read('public.dat').decode('ascii').splitlines();sas=z.read('check.sas').decode('latin1')
    assert len(lines)==len(NJ)==410 and 'EMPPT*.5 + EMPFT + NMGRS' in sas;stores=[{k:field(line,a,b) for k,a,b in spec} for line in lines]
    for o,r in zip(stores,NJ):
        for k,a,b in spec:
            if o[k] is None:assert r[k]==''
            else:same(o[k],r[k])
else:stores=[{k:Q(r[k]) if r[k] else None for k,a,b in spec} for r in NJ]
for o,r in zip(stores,NJ):
    for s in ['before','after']:
        ks=['ft_'+s,'pt_'+s,'managers_'+s];o['fte_'+s]=o[ks[0]]+o[ks[1]]/2+o[ks[2]] if all(o[k] is not None for k in ks) else None
        if o['fte_'+s] is None:assert r['fte_'+s]==''
        else:same(o['fte_'+s],r['fte_'+s])

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

# Every numeric input is an actual observation, not a case or previous metric JSON.
auditdir=WORKSPACE/'work/textbook-rewrite-2026/source-audit-data13';country=[];first=[]
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 archived official three-record response page',True);header,rs=json.loads(path.read_text(encoding='utf-8'),parse_float=D);assert header['page']==page and header['pages']==2 and header['total']==6
 for pos,r in enumerate(rs,1):
  row=dict(source_page=page,row_within_page=pos,ISO=r['countryiso3code'],year=int(r['date']),indicator_code=r['indicator']['id'],actual_GDPpc_constant2015USD_source_decimal=str(r['value']) if r['value'] is not None else '',source_lastupdated=header['lastupdated']);country.append(row)
  if page==1:first.append(row)
country.sort(key=lambda r:r['year']);verify('actual-six-Korea-GDP-source-records-with-page-keys.csv',country)
archive=raw/'proximity.zip'
if archive.is_file():
 with zipfile.ZipFile(archive) as z:lines=z.read('nls.dat').decode('ascii').splitlines()
 raws=[field(s,128,132) for s in lines]
else:
 path=DATA/'actual3613-separate-raw-log-fields-and-availability-contract.csv';S=read(path);note(path,'retained actual raw wage fields only; contract results are not inputs');raws=[Q(r['actual1976_raw_hourly_wage_cents']) if r['actual1976_raw_hourly_wage_cents'] else None for r in S]
P=[dict(source_row_id=i,original_person_code=str(o['person']),actual1976_raw_hourly_wage_cents=str(r) if r is not None else '',actual1976_source_trimmed_log_cents_per_hour=str(o['log_wage']) if o['log_wage'] is not None else '',raw_available=r is not None,source_log_available=o['log_wage'] is not None,source_trimming_rule_reconstructed=False) for i,(o,r) in enumerate(zip(people,raws),1)]
verify('actual3613-separate-raw-log-fields-and-availability-contract.csv',P);discord=[r for r in P if r['raw_available'] and not r['source_log_available']];verify('actual-seven-raw-wage-records-with-unavailable-trimmed-logs.csv',discord)
ns=[sum(r[k] for r in P) for k in ['raw_available','source_log_available']];logs=[o['log_wage'] for o in people if o['log_wage'] is not None];logmu=avg(logs);zero=sum(logs,Q(0))/len(P);availableRaw=[v for v in raws if v is not None]
denominators=[dict(field=fieldname,original_rows=len(P),available=len(v),unavailable=len(P)-len(v),available_source_mean_exact=avg(v),in_memory_zero_filled_mean_exact=sum(v,Q(0))/len(P),zero_filling_is_original_source=False) for fieldname,v in [('raw1976_wage_cents_per_hour',availableRaw),('source_trimmed_log1976_cents_per_hour',logs)]];verify('actual-two-field-denominators-and-invalid-zero-fill-comparison.csv',denominators)
N=[dict(source_row_id=i,original_store_code=str(o['store']),state='NJ' if o['nj']==1 else 'PA',chain=str(o['chain']),actual_FTE_before_exact=str(o['fte_before']) if o['fte_before'] is not None else '',actual_FTE_after_exact=str(o['fte_after']) if o['fte_after'] is not None else '',actual_paired_change_exact=str(o['fte_after']-o['fte_before']) if o['fte_after'] is not None and o['fte_before'] is not None else '',is_complete_original_row_pair=o['fte_after'] is not None and o['fte_before'] is not None,source_position_proves_independent_store_identity=False) for i,o in enumerate(stores,1)]
verify('actual410-stores-with-original-code-and-unique-source-row-key.csv',N);D407=[r for r in N if r['original_store_code']=='407'];verify('actual-two-distinct407-source-records.csv',D407);paired=[r for r in N if r['is_complete_original_row_pair']]
policies=[]
for name,drop in [('preserve_all_original_rows',None),('invalid_keep_first_code407_drop_row168',168),('invalid_keep_last_code407_drop_row42',42)]:
 rows=[r for r in N if r['source_row_id']!=drop];ps=[r for r in rows if r['is_complete_original_row_pair']];mu=avg([Q(r['actual_paired_change_exact']) for r in ps]);policies.append(dict(processing_policy=name,original_rows_kept=len(rows),original_complete_pairs_kept=len(ps),original_row_removed='' if drop is None else drop,mean_observed_change_exact=mu,source_is_modified=drop is not None,drop_is_validated_same_store_duplicate=False))
 for key,value in [('rows',len(rows)),('completePairs',len(ps)),('meanObservedChange',mu)]:add('company_policy'+str(len(policies)-1)+'_'+key,value)
verify('explicit-three-source-row-preservation-policies.csv',policies)
observed=[len(country)==6,len(first)==6,len({(r['ISO'],r['indicator_code'],r['year']) for r in country})==6,len(P)==3613,ns[0]==3017,ns[1]==3010,all(r['raw_available']==r['source_log_available'] for r in P),len(logs)==len(P),len({r['source_row_id'] for r in N})==410,len({r['original_store_code'] for r in N})==410,len(paired)==384,len(D407)==2 and {r['state'] for r in D407}=={'NJ','PA'}]
expected=[True,False,True,True,True,True,False,False,True,False,True,True]
checkIds=['both_pages_have_six_declared_keys','page_one_alone_is_complete_six_key_extract','ISO_indicator_year_keys_unique','all_3613_source_rows_preserved','raw_wage_availability_is3017','source_log_availability_is3010','raw_and_trimmed_log_availability_identical','zero_filled_logs_preserve_source_missingness','source_row_keys_unique410','original_store_codes_unique410','complete_pairs_are384','both407_source_rows_preserved']
path=DATA/'twelve-declared-contract-checks-with-expected-rejections.csv';S=read(path);note(path,'twelve rule results and expected rejections independently evaluated');assert len(S)==12
for i,(r,name,v,e) in enumerate(zip(S,checkIds,observed,expected)):
 assert r['check_id']==name and r['observed_rule_satisfied']==str(v) and r['expected_rule_satisfied']==str(e) and r['test_expectation_satisfied']==str(v==e)
 add('contract_check'+str(i)+'_observed',int(v));add('contract_check'+str(i)+'_expected',int(e));add('contract_check'+str(i)+'_expectationMet',int(v==e))
class ContractViolation(ValueError):pass
def require(condition):
 if not condition:raise ContractViolation('Declared contract not satisfied')
class ContractTests(unittest.TestCase):pass
for name,value,wanted in zip(checkIds,observed,expected):
 def test(self,value=value,wanted=wanted):
  if wanted:require(value);self.assertTrue(value)
  else:
   with self.assertRaises(ContractViolation):require(value)
 setattr(ContractTests,'test_'+name,test)
capture=io.StringIO();suite=unittest.defaultTestLoader.loadTestsFromTestCase(ContractTests);testresult=unittest.TextTestRunner(stream=capture,verbosity=1).run(suite);assert testresult.wasSuccessful() and testresult.testsRun==12
env=dict(chapter='DATA-14',runtime='Python',version=platform.python_version(),implementation=platform.python_implementation(),platform=sys.platform,machine=platform.machine(),byteorder=sys.byteorder,executionWasActual=True,framework='standard-library unittest',testsRun=testresult.testsRun,failures=len(testresult.failures),errors=len(testresult.errors),expectedRuleRejections=sum(not e for e in expected),codeFile='data14-reproduce.py',codeSha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),inputHashes=[dict(file=o['file'],sha256=o['sha256']) for o in AUDIT],noUsernameHostOrSecretEnvironmentRecorded=True)
(ROOT/'data14-python-environment.json').write_text(json.dumps(env,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
for key,value in dict(selectedRecords=len(country),firstPageRecords=len(first),semanticUniqueKeys=len({(r['ISO'],r['indicator_code'],r['year']) for r in country}),meanGDPpc=avg([Q(r['actual_GDPpc_constant2015USD_source_decimal']) for r in country])).items():add('country_'+key,value)
for key,value in dict(sourceRows=len(P),rawAvailable=ns[0],logAvailable=ns[1],rawUnavailable=len(P)-ns[0],logUnavailable=len(P)-ns[1],discordantRawLog=len(discord),availableRawMean=avg(availableRaw),availableLogMean=logmu,invalidZeroFilledLogMean=zero).items():add('person_'+key,value)
for i,row in enumerate(discord):add('person_discordant'+str(i)+'_sourceRow',row['source_row_id'])
for key,value in dict(sourceRows=len(N),distinctOriginalCodes=len({r['original_store_code'] for r in N}),completePairs=len(paired),incompleteRows=len(N)-len(paired),original407Records=len(D407)).items():add('company_'+key,value)
for r in D407:
 for key,v in [('before',r['actual_FTE_before_exact']),('after',r['actual_FTE_after_exact']),('change',r['actual_paired_change_exact'])]:add('company_407row'+str(r['source_row_id'])+'_'+key,Q(v))
add('contract_tests_total',testresult.testsRun);add('contract_expected_rejections',sum(not e for e in expected));add('contract_unexpected_failures',len(testresult.failures)+len(testresult.errors))
CHECKS.update(actualUnitTestsRun=12,expectedRuleRejections=4,unexpectedTestFailures=0,originalSourceObservationsUnchanged=True,invalidProcessingNeverOverwritesSource=True,environmentMetadataSeparateFromMetrics=True)

rpath=ROOT/'data14-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/'data14-results.json').write_text(json.dumps(dict(chapter='DATA-14',metrics=METRICS,exactFractions=EXACT,numericalApproximationMetrics=APPROX,inputAudit=AUDIT,checks=CHECKS,interpretation='Original public responses and fixed-width person/store records are numerical inputs. Twelve actual unittest checks include four expected rejections of unjustified contracts. Source missingness and both code407 records are preserved. Zero filling and deduplication are explicit invalid-processing comparisons, not producer revisions or validated cleaning. Hashes, runtime versions and tests support traceability within their scope, not accuracy, independence, representativeness or causal identification.'),ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
print('DATA-14:',len(METRICS),'actual-source metrics; R comparisons',CHECKS['RmetricComparisons'])
