"""ECON06 independent source reproduction (Python stdlib only).

Inputs: public econ06-sources original selected rows and location aggregates.
If the original UCI ZIP is retained in the workspace, independently stream its
XLSX XML and verify selected original cells and full location aggregates first.
No case/model JSON or prior numerical result supplies calculation inputs.
Source: Chen (2015), UCI Online Retail, DOI10.24432/C5BW33, CC BY4.0.
Original ZIP https://archive.ics.uci.edu/static/public/352/online%2Bretail.zip
Scope: one retailer, invoice lines, not nationally representative households.
"""
from pathlib import Path
from fractions import Fraction as F
from collections import defaultdict,Counter
from datetime import date,timedelta
from calendar import monthrange
import csv,json,hashlib,re,zipfile,io,xml.etree.ElementTree as ET
BASE=Path(__file__).resolve().parent;D=BASE/'econ06-sources'
def load(name):return list(csv.DictReader((D/name).open(encoding='utf-8-sig',newline='')))
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
stock=load('actual-source-order-selected-stock-all-lines.csv');account=load('actual-source-order-selected-account-all-lines.csv');geo=load('actual-all-line-country-label-aggregates.csv')
inputAudit={'calculationInputs':[dict(file='econ06-sources/'+name,sha256=sha(D/name)) for name in ['actual-source-order-selected-stock-all-lines.csv','actual-source-order-selected-account-all-lines.csv','actual-all-line-country-label-aggregates.csv']],'caseJSONUsedAsNumericInput':False,'exactMethod':'Fraction of original Quantity and UnitPrice decimal tokens','originalArchiveAuditExecuted':False}
archive=BASE.parent.parent/'work/textbook-rewrite-2026/source-audit-econ06/uci-online-retail352.zip';cellChecks=0
if archive.is_file():
    NS='{http://schemas.openxmlformats.org/spreadsheetml/2006/main}';z=zipfile.ZipFile(archive);raw=z.read('Online Retail.xlsx');book=zipfile.ZipFile(io.BytesIO(raw));ss=[''.join(x.itertext()) for x in ET.fromstring(book.read('xl/sharedStrings.xml')).findall(NS+'si')];selected={int(r['source_row_id']):r for r in stock+account};headers=None;loc=defaultdict(lambda:[0,0,F(),F()]);counts=Counter();firstStock=firstAccount=None
    with book.open('xl/worksheets/sheet1.xml') as f:
        for event,row in ET.iterparse(f,events=('end',)):
            if row.tag!=NS+'row':continue
            values={}
            for c in row.findall(NS+'c'):
                token=c.find(NS+'v');v=token.text if token is not None else None
                if c.get('t')=='s':v=ss[int(v)] if v is not None else None
                values[re.sub('[0-9]','',c.get('r'))]=v
            vals=[values.get(chr(65+j)) for j in range(8)]
            if headers is None:headers=vals;row.clear();continue
            r=dict(zip(headers,vals));sid=int(row.get('r'))-1;counts['originalRows']+=1;q=F(r['Quantity']);p=F(r['UnitPrice']);cancel=r['InvoiceNo'].upper().startswith('C');positive=q>0 and p>0 and not cancel
            counts['missingCustomer']+=r['CustomerID'] is None;counts['missingDescription']+=r['Description'] is None;counts['negativeQuantity']+=q<0;counts['cancellationLines']+=cancel
            g=loc[r['Country']];g[0]+=1;g[2]+=q*p
            if positive:g[1]+=1;g[3]+=q*p
            if firstStock is None and positive and r['Description'] and not r['StockCode'].isdigit():firstStock=r['StockCode']
            if firstAccount is None and positive and r['CustomerID'] is not None:firstAccount=r['CustomerID']
            if sid in selected:
                for h in headers:assert (r[h] or '')==selected[sid][h],(sid,h);cellChecks+=1
            row.clear()
    assert firstStock==stock[0]['StockCode'] and firstAccount==account[0]['CustomerID'];assert len(loc)==len(geo)
    for r in geo:
        g=loc[r['original_country_label']];assert g==[int(r['all_original_source_lines']),int(r['declared_positive_non_cancel_lines']),F(r['signed_recorded_line_amount_GBP_exact']),F(r['declared_positive_line_amount_GBP_exact'])];cellChecks+=4
    inputAudit.update(originalArchiveAuditExecuted=True,originalArchiveSHA256=sha(archive),originalWorkbookSHA256=hashlib.sha256(raw).hexdigest(),originalCounts=dict(counts),independentlyVerifiedOriginalCells=cellChecks)
else:inputAudit['originalArchiveUnavailableScope']='Calculations use retained actual selected source cells and public location aggregates; the full-workbook audit is not re-executed in this copy.'
M={};exact={}
def metric(name,v):v=F(v);exact[name]=str(v);M[name]=float(v)
def positive(r):return F(r['Quantity'])>0 and F(r['UnitPrice'])>0 and not r['InvoiceNo'].upper().startswith('C')
metric('source_location_labels',len(geo));metric('source_lines_from_location_totals',sum(int(r['all_original_source_lines']) for r in geo));metric('positive_lines_from_location_totals',sum(int(r['declared_positive_non_cancel_lines']) for r in geo))
for i,r in enumerate(geo,1):
    for field,suffix in [('all_original_source_lines','all_lines'),('declared_positive_non_cancel_lines','positive_lines'),('signed_recorded_line_amount_GBP_exact','signed_GBP'),('declared_positive_line_amount_GBP_exact','positive_GBP')]:metric(f'location_{i:02d}_{suffix}',r[field])
for prefix,rs in [('stock',stock),('account',account)]:
    metric(prefix+'_source_lines',len(rs));metric(prefix+'_positive_lines',sum(map(positive,rs)));metric(prefix+'_invoice_codes',len(set(r['InvoiceNo'] for r in rs)));metric(prefix+'_product_codes',len(set(r['StockCode'] for r in rs)));metric(prefix+'_cancellation_lines',sum(r['InvoiceNo'].upper().startswith('C') for r in rs));metric(prefix+'_signed_GBP',sum((F(r['Quantity'])*F(r['UnitPrice']) for r in rs),F()));metric(prefix+'_positive_GBP',sum((F(r['Quantity'])*F(r['UnitPrice']) for r in rs if positive(r)),F()))
inv={}
for r in account:
    code=r['InvoiceNo'];g=inv.setdefault(code,[0,F()]);g[0]+=1;g[1]+=F(r['Quantity'])*F(r['UnitPrice'])
for i,(code,(n,amount)) in enumerate(inv.items(),1):metric(f'invoice_{i:02d}_lines',n);metric(f'invoice_{i:02d}_signed_GBP',amount)
monthly=defaultdict(lambda:[0,F(),F()])
for r in stock:
    if positive(r):
        dt=date(1899,12,30)+timedelta(days=F(r['InvoiceDate']).numerator//F(r['InvoiceDate']).denominator);key=dt.strftime('%Y-%m');g=monthly[key];g[0]+=1;g[1]+=F(r['Quantity']);g[2]+=F(r['Quantity'])*F(r['UnitPrice'])
period={}
for month,(n,q,a) in sorted(monthly.items()):
    yy,mm=map(int,month.split('-'));days=9 if month=='2011-12' else monthrange(yy,mm)[1];p=a/q;daily=q/days;period[month]=(q,p,daily);stem='period_'+month.replace('-','_');metric(stem+'_lines',n);metric(stem+'_quantity',q);metric(stem+'_amount_GBP',a);metric(stem+'_weighted_price_GBP',p);metric(stem+'_units_per_calendar_day',daily);metric(stem+'_calendar_days',days)
q0,p0,d0=period['2011-01'];q1,p1,d1=period['2011-02'];gq=2*(d1-d0)/(d1+d0);gp=2*(p1-p0)/(p1+p0);mid=gq/gp;rawmid=(2*(q1-q0)/(q1+q0))/gp
for k,v in [('daily_midpoint_quantity_change',gq),('midpoint_price_change',gp),('daily_signed_midpoint_ratio',mid),('monthly_signed_midpoint_ratio',rawmid),('daily_signed_base_ratio',((d1-d0)/d0)/((p1-p0)/p0)),('daily_reversed_midpoint_ratio',(2*(d0-d1)/(d0+d1))/(2*(p0-p1)/(p0+p1))),('daily_pence_midpoint_ratio',gq/(2*(100*p1-100*p0)/(100*p1+100*p0)))]:metric(k,v)
assert M['daily_signed_midpoint_ratio']==M['daily_reversed_midpoint_ratio']==M['daily_pence_midpoint_ratio']
rfile=BASE/'econ06-r-results.csv';cross=0;tiny=0
if rfile.is_file():
    for r in csv.DictReader(rfile.open(encoding='utf-8-sig')):
        name=r['metric'];rv=float(r['value']);want=M[name];assert abs(rv-want)<=1e-9*max(1,abs(want)),(name,rv,want)
        if want and abs(want)<1e-9:assert abs(rv/want-1)<1e-8;tiny+=1
        cross+=1
    assert cross==len(M)
result={'metrics':M,'exactMetrics':exact,'inputAudit':inputAudit,'crossLanguageComparisons':cross,'tinyNonzeroRelativeComparisons':tiny,'scope':'Recorded source arithmetic and descriptive ratios, not identified demand, national consumer data or observed counterfactuals.'}
(BASE/'econ06-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf8');print(json.dumps({'metrics':len(M),'crossLanguage':cross,'originalCells':cellChecks,'originalArchiveAudit':inputAudit['originalArchiveAuditExecuted']}))
