"""Exercise feedback using independent contracts and counterexamples.

python3 labs/check_workshop.py mask
python3 labs/check_workshop.py all --reference
Exit 0 = passed, 1 = incorrect, 2 = unfinished TODO; --self-test audits checker.
"""
import argparse
import importlib
import json
import math
import random
from types import SimpleNamespace
from workshop_core import maxerr,softmax


def validate(module,selected='all'):
    checks=[]
    def require(ok,case):
        if not ok:raise AssertionError(json.dumps(case,ensure_ascii=False))
    def mask():
        count=0
        for past in [0,1,4,11]:
            for row in [0,1,3]:
                length=past+4;got=module.absolute_mask(row,past,length)
                require(isinstance(got,list) and len(got)==length,{'input':[row,past,length],'reason':'mask must be a list with key_length entries','got':got})
                for k,v in enumerate(got):require(type(v) is bool and v==(k-past<=row),{'input':[row,past,length],'key':k,'expected':k<=past+row,'got':v})
                count+=1
        return count
    def groups():
        count=0
        for hq,hkv in [(8,2),(8,1),(8,8),(12,3),(6,2)]:
            all_groups=[module.kv_group(h,hq,hkv) for h in range(hq)]
            for h,g in enumerate(all_groups):
                require(type(g) is int and 0<=g<hkv,{'Hq':hq,'Hkv':hkv,'head':h,'got':g})
                start=g*(hq//hkv);require(start<=h<start+hq//hkv,{'Hq':hq,'Hkv':hkv,'head':h,'group':g,'reason':'head must lie inside contiguous group interval'})
                count+=1
        return count
    def merge():
        count=0;rng=random.Random(819)
        for n in [1,5,11]:
            scores=[rng.uniform(-40,40) for _ in range(n)];values=[[rng.uniform(-3,3) for _ in range(3)] for _ in scores]
            probs=softmax(scores);expected=[sum(a*v[d] for a,v in zip(probs,values)) for d in range(3)]
            for tile in [1,2,4,n]:
                m,l,o=-math.inf,0.,[0.]*3
                for start in range(0,n,tile):m,l,o=module.merge_tile(m,l,o,scores[start:start+tile],values[start:start+tile])
                require(math.isfinite(l) and l>0 and len(o)==3,{'n':n,'tile':tile,'reason':'invalid accumulated denominator/shape'})
                actual=[x/l for x in o];require(maxerr(expected,actual)<1e-10,{'n':n,'tile':tile,'expected':expected,'got':actual,'reason':'rescale numerator and denominator to the same max'})
                count+=1
        return count
    def combine():
        routes=[(2,.7,[1.,2.]),(0,.25,[4.,-4.]),(2,.3,[3.,0.]),(0,.75,[0.,4.])]
        expected=[[1.,2.],[0.,0.],[1.6,1.4],[0.,0.]];count=0
        for order in [routes,list(reversed(routes)),routes[2:]+routes[:2],[]]:
            got=module.combine(4,2,order);want=expected if order else [[0.,0.] for _ in range(4)]
            require(isinstance(got,list) and len(got)==4 and all(len(r)==2 for r in got),{'reason':'output must include all token rows, including empty routes'})
            require(maxerr(got,want)<1e-12,{'routes':order,'expected':want,'got':got});count+=1
        return count
    for key,fn in [('mask',mask),('gqa',groups),('online',merge),('moe',combine)]:
        if selected not in ('all',key):continue
        try:checks.append({'exercise':key,'status':'passed','cases':fn()})
        except NotImplementedError as e:checks.append({'exercise':key,'status':'todo','message':str(e)})
        except Exception as e:checks.append({'exercise':key,'status':'failed','counterexample':str(e)})
    return checks
def self_test():
    assert maxerr([0.,float('nan')],[0.,0.])==math.inf
    try:maxerr([0.],[0.,0.])
    except ValueError:pass
    else:raise AssertionError('Shape mismatch was silently truncated')
    ref=importlib.import_module('workshop_solutions');good=validate(ref)
    assert all(x['status']=='passed' for x in good)
    # Representative bugs must be rejected, not accidentally accepted by the rubric.
    for key,field,fn in [
        ('mask','absolute_mask',lambda row,past,n:[k<=row for k in range(n)]),
        ('gqa','kv_group',lambda h,hq,hkv:h%hkv),
        ('online','merge_tile',lambda m,l,o,s,v:(max(s),len(s),[sum(row[d] for row in v) for d in range(len(o))])),
        ('moe','combine',lambda n,d,r:[[1.]*d for _ in range(n)]),
    ]:
        broken=SimpleNamespace(**{name:getattr(ref,name) for name in ['absolute_mask','kv_group','merge_tile','combine']});setattr(broken,field,fn)
        assert validate(broken,key)[0]['status']=='failed'
    return {'reference_cases':sum(x['cases'] for x in good),'caught_mutations':4,'errors':[]}
def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('exercise',choices=['all','mask','gqa','online','moe'],nargs='?',default='all');p.add_argument('--reference',action='store_true');p.add_argument('--self-test',action='store_true');a=p.parse_args()
    if a.self_test:print(json.dumps(self_test(),indent=2));return
    checks=validate(importlib.import_module('workshop_solutions' if a.reference else 'workshop_student'),a.exercise)
    print(json.dumps({'implementation':'reference' if a.reference else 'student','checks':checks,'note':'Passing reference solutions does not certify your own mastery.'},ensure_ascii=False,indent=2))
    raise SystemExit(1 if any(x['status']=='failed' for x in checks) else 2 if any(x['status']=='todo' for x in checks) else 0)
if __name__=='__main__':main()
