"""ECON10: original public sources, not case JSON or prior numeric summaries.
Original HTML/XLSX archives are preferred. Supplied actual-value CSVs are a
declared portable fallback, preserving source tokens and positions.
"""
from pathlib import Path
from fractions import Fraction as F
from collections import Counter
from decimal import Decimal as D,ROUND_HALF_UP
from html.parser import HTMLParser
import json,csv,hashlib,zipfile,io,re,html,math
import xml.etree.ElementTree as ET
HERE=Path(__file__).resolve().parent;ROOT=HERE.parents[1];DATA=HERE/'econ10-sources';ARCH=ROOT/'work/textbook-rewrite-2026/source-audit-econ10'
metrics={};exact={};audits=[];checks=0
def read(path):
    with path.open(encoding='utf-8-sig',newline='') as s:return list(csv.DictReader(s))
def note(path,purpose,original=False):audits.append(dict(file=str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path),sha256=hashlib.sha256(path.read_bytes()).hexdigest(),purpose=purpose,archivedOriginalUsed=original))
def add(k,v):v=F(v);metrics[k]=float(v);exact[k]=str(v)
def same(a,b):
    global checks
    checks+=1;assert F(a)==F(b),(a,b)
class Rows(HTMLParser):
    def __init__(self):super().__init__();self.rows=[];self.row=None;self.cell=None;self.skip=0
    def handle_starttag(self,t,a):
        if t in ['script','style']:self.skip+=1
        if self.skip:return
        if t=='tr':self.row=[]
        if t in ['td','th'] and self.row is not None:self.cell=[]
    def handle_data(self,s):
        if not self.skip and self.cell is not None:self.cell.append(s)
    def handle_endtag(self,t):
        if t in ['script','style']:self.skip-=1;return
        if self.skip:return
        if t in ['td','th'] and self.cell is not None:self.row.append(' '.join(''.join(self.cell).split()));self.cell=None
        if t=='tr' and self.row is not None:self.rows.append(self.row);self.row=None
bp=ARCH/'BTS-domestic-market-share-snapshot.html';sr=read(DATA/'actual-BTS-carrier-RPM-share-labels-and-raw-tokens.csv')
if bp.is_file():
    note(bp,'official domestic RPM share table and title',True);h=bp.read_text(encoding='utf8');assert 'August 2025 - July 2026' in h and 'Domestic Revenue Passenger Miles' in h
    fragment=h[h.index('Airline Domestic Market Share August 2025 - July 2026'):];fragment=fragment[:fragment.index('</TABLE>')];p=Rows();p.feed(fragment)
    original=[r for r in p.rows if len(r)==2 and r[1].endswith('%')];assert len(original)==11
    for o,r in zip(original,sr):assert o[0]==r['carrier_label'] and o[1][:-1]==r['source_share_percent_token'];same(F(D(o[1][:-1]).quantize(D('.1'),rounding=ROUND_HALF_UP)),r['chosen_one_decimal_display_percent_exact'])
    sourceRPM=[s for s in re.search(r'var sData = "([^"]+)"',h).group(1).split(',') if s]
    assert sourceRPM==[r['source_RPM_billions_display_token'] for r in sr[:-1]]
    for token,row in zip(sourceRPM,sr):same(token,row['source_RPM_billions_display_token'])
else:note(DATA/'actual-BTS-carrier-RPM-share-labels-and-raw-tokens.csv','portable actual source share/token selection')
s=[F(D(r['source_share_percent_token']).quantize(D('.1'),rounding=ROUND_HALF_UP)) for r in sr];assert sum(s)==100
for i,r in enumerate(sr):
    add(f'country_share{i}',s[i])
    if r['source_RPM_billions_display_token']:add(f'country_RPMbillions{i}',r['source_RPM_billions_display_token'])
CR4=sum(s[:4]);known=sum(x*x for x in s[:-1]);other=s[-1]
for k,v in [('CR4_percent',CR4),('known10_squared',known),('Other_display_percent',other),('grouped11_HHI',known+other*other)]:add('country_'+k,v)
sens=read(DATA/'hypothetical-Other-split-concentration-sensitivity.csv')
for row in sens:
    m=int(row['hypothetical_equal_other_carriers']);value=known+other*other/m;add('country_assumed_m'+str(m)+'_HHI',value)
    for key,val in [('published_top4_display_CR4_percent_exact',CR4),('known10_squared_display_shares_exact',known),('assumed_other_contribution_exact',other*other/m),('conditional_display_HHI_exact',value)]:same(val,row[key])
rr=read(DATA/'actual17-same-day-same-stock-positive-lines.csv');zp=ROOT/'work/textbook-rewrite-2026/source-audit-econ06/uci-online-retail352.zip'
if zp.is_file():
    note(zp,'original541909 retail invoice-item rows',True)
    with zipfile.ZipFile(zp) as z:book=zipfile.ZipFile(io.BytesIO(z.read('Online Retail.xlsx')))
    NS='{http://schemas.openxmlformats.org/spreadsheetml/2006/main}';strings=[''.join(e.itertext()) for e in ET.fromstring(book.read('xl/sharedStrings.xml')).findall(NS+'si')]
    selected=[];originalCount=0;names=['InvoiceNo','StockCode','Description','Quantity','InvoiceDate','UnitPrice','CustomerID','Country']
    with book.open('xl/worksheets/sheet1.xml') as stream:
        for _,row in ET.iterparse(stream,events=('end',)):
            if row.tag!=NS+'row':continue
            if row.get('r')=='1':row.clear();continue
            originalCount+=1;cells={}
            for c in row.findall(NS+'c'):
                v=c.find(NS+'v');v=v.text if v is not None else ''
                if c.get('t')=='s':v=strings[int(v)]
                cells[re.sub('[0-9]','',c.get('r'))]=v
            raw=[cells.get(chr(65+i),'') for i in range(8)]
            if raw[1]=='85123A' and F(raw[3])>0 and F(raw[5])>0 and not raw[0].upper().startswith('C') and int(D(raw[4]))==40513:selected.append((int(row.get('r'))-1,raw))
            row.clear()
    assert originalCount==541909 and len(selected)==17
    for (pos,raw),r in zip(selected,rr):
        same(pos,r['source_row_id'])
        for key,val in zip(names,raw):assert r[key]==val;checks+=1
else:note(DATA/'actual17-same-day-same-stock-positive-lines.csv','portable preserved actual8-field invoice-line selection')
assert len(rr)==17
for i,r in enumerate(rr):
    for k,v in [('row',r['source_row_id']),('quantity',r['Quantity']),('price',r['UnitPrice']),('amount',F(r['Quantity'])*F(r['UnitPrice']))]:add(f'person_line{i}_{k}',v)
    same(F(r['UnitPrice']),r['unit_price_GBP_exact']);same(F(r['Quantity'])*F(r['UnitPrice']),r['recorded_line_amount_GBP_exact'])
six=[r for r in rr if F(r['Quantity'])==6];add('person_selected_rows',len(rr));add('person_missing_account_rows',sum(not r['CustomerID'] for r in rr));add('person_quantity6_rows',len(six));add('person_quantity6_available_distinct_accounts',len({r['CustomerID']for r in six if r['CustomerID']}))
groups=read(DATA/'actual-same-day-price-groups-and-denominators.csv')
for i,price in enumerate(sorted({F(r['UnitPrice']) for r in rr})):
    g=[r for r in rr if F(r['UnitPrice'])==price];values=dict(source_lines=len(g),available_account_lines=sum(bool(r['CustomerID'])for r in g),distinct_available_account_codes=len({r['CustomerID']for r in g if r['CustomerID']}),quantity6_lines=sum(F(r['Quantity'])==6 for r in g))
    same(groups[i]['source_unit_price_GBP_exact'],price)
    for key,value in values.items():same(groups[i][key],value);add(f'person_pricegroup{i}_{key}',value)
spread=F('2.95')-F('2.5499999999999998');add('person_equal6_pricegap',spread);add('person_equal6_amountgap',6*spread)
gap=read(DATA/'actual-equal-six-item-recorded-price-gap.csv')[0];same(gap['recorded_unit_price_gap_GBP_exact'],spread);same(gap['six_item_amount_gap_GBP_exact'],6*spread)
cp=ARCH/'Southwest-2024-official10K.html';ar=read(DATA/'actual-Southwest2024-10K-financial-and-traffic-records.csv')
if cp.is_file():
    note(cp,'original issuer Form10K financial/traffic rows',True);source=Rows();source.feed(cp.read_text(encoding='utf8'))
    for row in ar:
        matches=[]
        for cells in source.rows:
            c=[x for x in cells if x and x not in ['$','%']]
            if c and re.sub(r'\s+','',c[0]).lower()==re.sub(r'\s+','',row['source_row_label']).lower():
                v=[x.replace(',','')for x in c[1:]if re.fullmatch(r'[0-9,]+(?:\.[0-9]+)?',x)]
                if len(v)==3:matches.append(v)
        year=int(row['fiscal_year']);idx=2024-year
        # The original income statement is selected by its full three-year
        # source row; comparative change-percent rows are not substitutes.
        wanted=[r['source_value_token'] for r in ar if r['metric']==row['metric']]
        if len(wanted)==3:assert wanted in matches,(row,wanted,matches)
        else:assert any(m[:2]==wanted for m in matches),(row,wanted,matches)
        assert any(F(m[idx])==F(row['source_value_token'])for m in matches);checks+=1
else:note(DATA/'actual-Southwest2024-10K-financial-and-traffic-records.csv','portable selected actual issuer values')
v={(int(r['fiscal_year']),r['metric']):F(r['source_value_token'])for r in ar}
for (year,key),value in v.items():add(f'company_{year}_{key}',value)
ratios=read(DATA/'actual-accounting-ratios-and-average-not-marginal.csv')
for year in [2023,2024]:
    R,C,I,PR,Q,RM,AS=[v[year,k]for k in ['operating_revenue_million_USD','operating_expense_million_USD','operating_income_million_USD','passenger_revenue_million_USD','revenue_passengers_thousands','RPM_millions','ASM_millions']];same(R-C,I)
    row=next(r for r in ratios if int(r['fiscal_year'])==year)
    values=dict(actual_operating_margin_fraction_exact=I/R,derived_passenger_revenue_per_revenue_passenger_USD_exact=1000*PR/Q,reported_average_passenger_fare_USD_exact=v[year,'average_passenger_fare_USD'],derived_operating_cost_per_revenue_passenger_USD_exact=1000*C/Q,derived_load_factor_exact=RM/AS)
    for k,value in values.items():same(value,row[k]);add(f'company_{year}_{k}',value)
Q0=v[2024,'revenue_passengers_thousands']/1000;P0=v[2024,'passenger_revenue_million_USD']/Q0
profiles=read(DATA/'hypothetical-scale-only-monopoly-Cournot-models.csv')
for row in profiles:
    n=int(row['hypothetical_identical_firms']);q=F(3*n,2*(n+1));p=2*P0-P0*q;c=P0/2;profit=Q0*q*(p-c);cs=Q0*P0*q*q/2;best=Q0*P0*F(9,8)
    values=dict(borrowed_quantity_scale_million_passengers_exact=Q0,borrowed_price_scale_USD_per_passenger_exact=P0,assumed_total_quantity_index_exact=q,assumed_total_quantity_million_exact=q*Q0,assumed_price_USD_exact=p,assumed_constant_MC_USD_exact=c,assumed_industry_operating_profit_million_USD_exact=profit,assumed_consumer_surplus_million_USD_exact=cs,assumed_total_surplus_million_USD_exact=profit+cs,assumed_DWL_million_USD_exact=best-profit-cs)
    for key,value in values.items():same(value,row[key]);add(f'model_n{n}_{key}',value)
    # Direct best-response first-order equation with others held fixed.
    qi=q/n;same(2*P0-P0*(q-qi)-2*P0*qi,c)
pr=read(DATA/'hypothetical-two-segment-price-comparison.csv');totals={}
for regime in ['uniform','segmented']:
    total=[F(),F(),F()]
    for group,intercept in [('A',200),('B',120)]:
        p=F(100)if regime=='uniform'else F(intercept+40,2);q=intercept-p;profit=(p-40)*q;cs=q*q/2
        row=next(r for r in pr if r['hypothetical_rule']==regime and r['hypothetical_group']==group)
        values=dict(chosen_price_exact=p,assumed_quantity_exact=q,assumed_profit_money_units_exact=profit,assumed_CS_money_units_exact=cs,assumed_total_surplus_money_units_exact=profit+cs)
        for key,value in values.items():same(value,row[key]);add(f'pricing_{regime}_{group}_{key}',value)
        total=[a+b for a,b in zip(total,[profit,cs,profit+cs])]
    for key,value in zip(['profit','CS','TS'],total):add(f'pricing_{regime}_total_{key}',value)
    totals[regime]=total
assert totals['uniform']==[7200,5200,12400] and totals['segmented']==[8000,4000,12000]
for path in sorted(DATA.glob('*.csv')):note(path,'actual selected values or explicitly chosen derived scenarios')
Rpath=HERE/'econ10-r-results.csv';Rchecks=0
if Rpath.is_file():
    R={r['metric']:float(r['value'])for r in read(Rpath)};assert set(R)==set(metrics),(set(R)^set(metrics))
    for key,value in metrics.items():
        assert abs(R[key]-value)<=1e-10*max(1,abs(value)),(key,R[key],value)
        if 0<abs(value)<1e-9:assert abs(R[key]/value-1)<=1e-8,(key,R[key],value)
        Rchecks+=1
result=dict(chapter='ECON-10',metrics=metrics,exactFractions=exact,inputAudit=audits,checks=dict(originalPreferred=True,caseJSONNumericInput=False,priorResultsNumericInput=False,exactSelectedCSVValuesCompared=checks,RmetricComparisons=Rchecks,actualShareRoundingNotInferredPrecision=True,marketPowerOrDiscriminationIdentified=False,monopolyCournotAndSegmentCurvesAreAssumed=True))
(HERE/'econ10-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print('ECON10:',len(metrics),'actual/scenario metrics; R comparisons',Rchecks,'source/derived checks',checks)
