"""Reproduce ECON11 from original official PDFs or disclosed selected-fact CSVs.
No cases JSON, model contract, previous results or R output is a calculation input.
Run beside econ11-sources/. Standard-library Python plus optional pdftotext.
Original PDFs stay in the internal source audit; redistribution is not required.
"""
from pathlib import Path
from fractions import Fraction as F
import csv,json,hashlib,subprocess,re,shutil
O=Path(__file__).resolve().parent;D=O/'econ11-sources';A=O.parents[1]/'work/textbook-rewrite-2026/source-audit-econ11'
metrics={};exact={};audit={};comparisons=0
def put(k,v):
    q=F(v);metrics[k]=float(q);exact[k]=str(q)
def read(n):
    p=D/n;audit[n]={'file':str(p),'sha256':hashlib.sha256(p.read_bytes()).hexdigest()};return list(csv.DictReader(p.open(encoding='utf8',newline='')))
def raw(n):
    p=A/n
    if p.exists()and shutil.which('pdftotext'):
        audit[n]={'file':str(p),'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'mode':'original PDF via independent pdftotext call'}
        return subprocess.check_output(['pdftotext','-layout',str(p),'-'],text=True,encoding='utf8')
    return None
country=read('actual-2013-UK-auction-rounded-official-report.csv');original=raw('NAO-4g-auction-summary-2014.pdf')
if original is not None:
    rr=re.findall(r'^\s*(EE|Niche \(BT\) \(new entrant\)|O2|Three|Vodafone)\s+(\d+)\s+(\d+)\s+(\d+)\s*$',original,re.M)
    assert len(rr)==5
    for r,(name,a,b,pay)in zip(country,rr):
        assert(r['winner_label'],r['reported_800MHz_share_percent'],r['reported_2_6GHz_share_percent'],r['reported_price_million_GBP'])==(name,a,b,pay);comparisons+=4
else:audit['countryFallback']='original unavailable; independently selected factual CSV used'
for r in country:
    key=r['winner_label'].split()[0]
    for col in ['reported_800MHz_share_percent','reported_2_6GHz_share_percent','reported_price_million_GBP']:put('country_'+key+'_'+col,r[col])
put('country_total_million_GBP',sum(F(r['reported_price_million_GBP'])for r in country))
put('country_800MHz_total_percent',sum(F(r['reported_800MHz_share_percent'])for r in country));put('country_2_6GHz_total_percent',sum(F(r['reported_2_6GHz_share_percent'])for r in country))
rounds=read('actual-2022-final-shootout-paired-rounds.csv');attempts=read('actual-2022-final-eight-shootout-attempts.csv');totals=read('actual-2022-final-match-versus-shootout.csv');original=raw('FIFA-final2022-match-report.pdf')
if original is not None:
    block=original.split('PENALTY SHOOT-OUT',1)[1].split('VAR',1)[0]
    rr=re.findall(r'^\s*([A-Z ]+[a-z][A-Za-z ]*)\s+\[(\d+)\]\s+(\d+)\s*-\s*(\d+)\s+([A-Z ]+[a-z][A-Za-z ]*)\s+\[(\d+)\]\s*$',block,re.M);assert len(rr)==4
    prev=[0,0]
    for i,(a,shirtA,ca,cb,b,shirtB)in enumerate(rr):
        r=rounds[i];assert(r['argentina_name'],r['argentina_shirt'],r['france_name'],r['france_shirt'],r['argentina_cumulative'],r['france_cumulative'])==(a.strip(),shirtA,b.strip(),shirtB,ca,cb);comparisons+=6
        for j,(team,name,shirt,cum)in enumerate([('ARG',a.strip(),shirtA,int(ca)),('FRA',b.strip(),shirtB,int(cb))]):
            s=attempts[2*i+j];assert(s['team'],s['player_source_label'],s['shirt'],int(s['scored']))==(team,name,shirt,cum-prev[j]);comparisons+=4;prev[j]=cum
    x=re.search(r'(\d+)\s*/\s*(\d+)\s+Penalties \(total/scored\)\s+(\d+)\s*/\s*(\d+)',original);assert x
    assert[(str(v['in_match_penalties']),str(v['in_match_scored']))for v in totals]==[(x[1],x[2]),(x[3],x[4])];comparisons+=4
else:audit['personFallback']='original unavailable; independently selected factual CSV used'
for i,r in enumerate(attempts):put('person_attempt_'+str(i+1)+'_scored',r['scored'])
for team in ['ARG','FRA']:
    ss=[r for r in attempts if r['team']==team];put('person_'+team+'_attempts',len(ss));put('person_'+team+'_goals',sum(int(r['scored'])for r in ss));put('person_'+team+'_frequency',F(sum(int(r['scored'])for r in ss),len(ss)))
for r in totals:put('person_'+r['team']+'_in_match_attempts',r['in_match_penalties']);put('person_'+r['team']+'_in_match_goals',r['in_match_scored'])
put('person_all_attempts',len(attempts));put('person_all_goals',sum(int(r['scored'])for r in attempts));put('person_all_frequency',F(sum(int(r['scored'])for r in attempts),len(attempts)))
# Explicit classroom assumptions, independently computed, not actual valuations.
def pay(a,b):
    if a>=b:return b,12-b,0
    return a,0,8-a
profiles=read('hypothetical-single-item-second-price-profiles.csv');ne=[]
for r in profiles:
    a,b=int(r['bid_A']),int(r['bid_B']);price,ua,ub=pay(a,b);ba=max(pay(x,b)[1]for x in range(13));bb=max(pay(a,y)[2]for y in range(13));vals={'price':price,'utility_A':ua,'utility_B':ub,'A_is_best_response':int(ua==ba),'B_is_best_response':int(ub==bb),'pure_Nash':int(ua==ba and ub==bb)}
    for key,val in vals.items():assert F(r[key])==val;comparisons+=1;put(f'auction_{a}_{b}_{key}',val)
    if vals['pure_Nash']:ne.append((a,b))
assert(12,8)in ne and(0,12)in ne
put('auction_pure_Nash_count',len(ne));put('auction_truthful_A_payoff',pay(12,8)[1]);put('auction_truthful_B_payoff',pay(12,8)[2])
put('auction_truthful_A_weak_dominance',all(pay(12,b)[1]>=pay(a,b)[1]for a in range(13)for b in range(13)));put('auction_truthful_B_weak_dominance',all(pay(a,8)[2]>=pay(a,b)[2]for a in range(13)for b in range(13)))
matrix=read('hypothetical-kicker-keeper-payoffs.csv');P=[[F(3,10),F(9,10)],[F(4,5),F(2,5)]]
for r in matrix:
    i=['L','R'].index(r['kicker_action']);j=['L','R'].index(r['keeper_action']);assert F(r['assumed_goal_probability'])==P[i][j]and F(r['assumed_keeper_payoff'])==1-P[i][j];comparisons+=2
pmix=(P[1][0]-P[1][1])/(P[0][1]-P[1][1]-P[0][0]+P[1][0]);qmix=(P[0][1]-P[1][1])/(P[1][0]-P[1][1]-P[0][0]+P[0][1]);value=pmix*P[0][0]+(1-pmix)*P[1][0]
put('kick_mixed_pL',pmix);put('kick_mixed_qL',qmix);put('kick_mixed_value',value)
for r in read('hypothetical-kicker-mixing-profile.csv'):
    p=F(r['kicker_L_probability']);u=p*P[0][0]+(1-p)*P[1][0];v=p*P[0][1]+(1-p)*P[1][1]
    for key,x in [('goal_if_keeper_L',u),('goal_if_keeper_R',v),('goal_against_best_responding_keeper',min(u,v))]:assert F(r[key])==x;comparisons+=1;put('kick_p'+str(p)+'_'+key,x)
E=[[F(0),F(0)],[F(1),F(-1)]];I=[[F(4),F(4)],[F(2),F(1)]];entry=read('hypothetical-entry-normal-form.csv')
for r in entry:
    i=['out','in'].index(r['entrant_plan']);j=['accommodate_if_entry','fight_if_entry'].index(r['incumbent_contingent_plan']);vals={'assumed_entrant_payoff':E[i][j],'assumed_incumbent_payoff':I[i][j],'entrant_best_response':int(E[i][j]==max(E[x][j]for x in range(2))),'incumbent_best_response':int(I[i][j]==max(I[i][y]for y in range(2))),'pure_Nash':int(E[i][j]==max(E[x][j]for x in range(2))and I[i][j]==max(I[i][y]for y in range(2))),'subgame_perfect':int(i==1 and j==0)}
    for key,v in vals.items():assert F(r[key])==v;comparisons+=1;put(f'entry_{i}_{j}_{key}',v)
for r in read('hypothetical-entry-response-profile.csv'):
    q=F(r['incumbent_accommodate_probability']);u=q*E[1][0]+(1-q)*E[1][1];assert F(r['entrant_expected_payoff_if_in'])==u;comparisons+=1;put('entry_q'+str(q)+'_in_payoff',u)
for r in read('hypothetical-entry-sunk-constant-invariance.csv'):
    i=['out','in'].index(r['entrant_plan']);j=['accommodate_if_entry','fight_if_entry'].index(r['incumbent_contingent_plan']);s=F(r['chosen_common_sunk_constant']);assert F(r['incumbent_payoff_net_of_chosen_constant'])==I[i][j]-s;comparisons+=1;put(f'entry_sunk_{s}_{i}_{j}',I[i][j]-s)
put('company_actual_Vodafone_reported_million_GBP',next(r['reported_price_million_GBP']for r in country if r['winner_label']=='Vodafone'))
result={'chapter':'ECON-11','metrics':metrics,'exactMetrics':exact,'inputAudit':audit,'selectedCellComparisons':comparisons,'assumptions':'Finite second-price auction, kick goal matrix and entry payoffs are chosen teaching models; no actual strategic identification.'}
(O/'econ11-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print('ECON11 Python:',len(metrics),'metrics;',comparisons,'selected/source comparisons')
