"""METR11 standalone public exact descriptive contrasts; stdlib and three public selection CSVs only."""
from pathlib import Path
from fractions import Fraction as F
from collections import defaultdict
import csv,json,hashlib,sys,platform,os
BASE=Path(sys.argv[1]).resolve()if len(sys.argv)>1 else Path(__file__).resolve().parent
DATA=BASE/'metr11-sources'
FILES={'country':'actual96-country-2018-2023-life-fixed-2019-income-groups.csv','person':'actual10839-person-wage-1976-1978-1980-nearc4-groups.csv','company':'actual820-store-before-after-staffing-state-groups.csv'}
REFERENCE={'country':'2019','person':'1976','company':'before'}
POST={'country':'2020','person':'1980','company':'after'}
def writecsv(name,rows):
 with(DATA/name).open('w',encoding='utf-8-sig',newline='')as f:
  w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows({k:''if v is None else str(v)for k,v in r.items()}for r in rows)
def calculate():
 metrics={};summaries=[];wave=[];event=[];changes=[];inputs=[]
 for kind,name in FILES.items():
  path=DATA/name
  with path.open(encoding='utf-8-sig',newline='')as f:raw=list(csv.DictReader(f))
  groups=defaultdict(list);times=list(dict.fromkeys(r['time']for r in raw));seen=set()
  for r in raw:
   address=(r['unit'],r['time'])
   if address in seen:raise ValueError('duplicate unit/time source address')
   seen.add(address)
   if r['group']not in ['','0','1']:raise ValueError('group must be0/1 or missing')
   groups[r['unit']].append(r)
  for rs in groups.values():
   if len({r['group']for r in rs if r['group']!=''})>1:raise ValueError('group must be fixed within unit')
  full={u:rs for u,rs in groups.items()if len(rs)==len(times)and all(r['group']!=''and r['y']!=''for r in rs)}
  gc={g:sum(rs[0]['group']==str(g)for rs in full.values())for g in [0,1]}
  if min(gc.values())==0:raise ValueError('both groups require positive full-wave unit counts')
  if REFERENCE[kind]not in times or POST[kind]not in times:raise ValueError('reference/post source wave missing')
  summary=dict(kind=kind,originalEntries=len(raw),originalUnits=len(groups),fullWaveUnits=len(full),fullWaveEntries=len(full)*len(times),group0Units=gc[0],group1Units=gc[1],excludedUnits=len(groups)-len(full))
  summaries.append(summary)
  for k,v in summary.items():
   if k!='kind':metrics[kind+'.structure.'+k]=str(v)
  means={}
  for time in times:
   means[time]={}
   for g in [0,1]:
    values=[F(next(r['y']for r in rs if r['time']==time))for rs in full.values()if rs[0]['group']==str(g)];mu=sum(values)/len(values);means[time][g]=mu;wave.append(dict(kind=kind,time=time,group=g,unitCount=len(values),meanY=mu))
  base=means[REFERENCE[kind]]
  for time in times:
   m=means[time];d0=m[0]-base[0];d1=m[1]-base[1];did=d1-d0;row=dict(kind=kind,time=time,referenceTime=REFERENCE[kind],group0Units=gc[0],group1Units=gc[1],group0Mean=m[0],group1Mean=m[1],group0Change=d0,group1Change=d1,observedDID=did);event.append(row)
   for k in ['group0Units','group1Units','group0Mean','group1Mean','group0Change','group1Change','observedDID']:metrics[kind+'.event.'+time+'.'+k]=str(row[k])
  p=means[POST[kind]]
  for k,v in dict(controlPre=base[0],controlPost=p[0],group1Pre=base[1],group1Post=p[1],controlChange=p[0]-base[0],group1Change=p[1]-base[1],observedDID=p[1]-base[1]-p[0]+base[0]).items():metrics[kind+'.default.'+k]=str(v)
  for unit,rs in full.items():
   pre=next(r for r in rs if r['time']==REFERENCE[kind]);post=next(r for r in rs if r['time']==POST[kind]);changes.append(dict(kind=kind,unit=unit,sourceCode=pre['code'],group=pre['group'],referenceTime=REFERENCE[kind],postTime=POST[kind],preY=F(pre['y']),postY=F(post['y']),observedChange=F(post['y'])-F(pre['y'])))
  inputs.append(dict(file=name,rows=len(raw),sha256=hashlib.sha256(path.read_bytes()).hexdigest()))
 writecsv('derived3-common-full-wave-selection-summary.csv',summaries);writecsv('derived22-common-full-wave-group-means.csv',wave);writecsv('derived11-common-full-wave-event-contrasts.csv',event);writecsv('derived2507-common-full-wave-unit-changes.csv',changes)
 return dict(chapter='METR-11',scope='Observed common-full-wave group contrasts,not certified ATT;uniform working weights1;no original archives required',metrics=metrics,inputAudit=inputs,reference=REFERENCE,defaultPost=POST,runtime=dict(Python=platform.python_version(),LC_ALL=os.environ.get('LC_ALL'),TZ=os.environ.get('TZ')))
if __name__=='__main__':
 result=calculate();(BASE/'metr11-results.json').write_bytes((json.dumps(result,ensure_ascii=False,indent=2)+'\n').encode());print(json.dumps(dict(metrics=len(result['metrics']),undefined=sum(v is None for v in result['metrics'].values()))))
