"""Account-free synthetic evaluation and policy fixtures; not authentication."""
from fractions import Fraction
import json

SCORES=[('A',1,'0.9'),('B',0,'0.8'),('C',1,'0.7'),('D',0,'0.6'),('E',1,'0.4'),('F',0,'0.3'),('G',0,'0.2'),('H',0,'0.1')]
ORDERS={'O1':'alice','O2':'bob'}
ACTORS={'alice':'customer','bob':'customer','worker':'operator','manager':'approver'}

def permitted(actor,action,order):
    if actor not in ACTORS or order not in ORDERS:return False
    role=ACTORS[actor]
    if action=='view':return role in ['operator','approver'] or ORDERS[order]==actor
    if action=='approve':return role=='approver'
    return False

def evaluate(rows,threshold='0.5',fp_cost=10,fn_cost=50):
    threshold=Fraction(threshold)
    if not 0<=threshold<=1:raise ValueError('threshold must be within 0..1')
    if any(type(v) is not int or v<0 for v in [fp_cost,fn_cost]):raise ValueError('error costs must be non-negative integers')
    counts=dict(tp=0,fp=0,fn=0,tn=0);seen=set()
    for identifier,label,score in rows:
        if not isinstance(identifier,str) or not identifier.strip() or identifier in seen:raise ValueError('unique non-empty identifiers required')
        if type(label) is not int or label not in [0,1]:raise ValueError('labels must be integer 0 or 1')
        score=Fraction(score)
        if not 0<=score<=1:raise ValueError('score must be within 0..1')
        seen.add(identifier);predicted=score>=threshold
        key=('tp' if label else 'fp') if predicted else ('fn' if label else 'tn');counts[key]+=1
    def ratio(n,d):return Fraction(n,d) if d else None
    return dict(**counts,accuracy=ratio(counts['tp']+counts['tn'],len(seen)),precision=ratio(counts['tp'],counts['tp']+counts['fp']),recall=ratio(counts['tp'],counts['tp']+counts['fn']),flagged=counts['tp']+counts['fp'],loss=counts['fp']*fp_cost+counts['fn']*fn_cost)

def fictional_cloud_cost(requests,rate='0.001',storage=2,transfer=3):
    if type(requests) is not int or requests<0:raise ValueError('requests must be a non-negative integer')
    amounts=[Fraction(rate),Fraction(storage),Fraction(transfer)]
    if min(amounts)<0:raise ValueError('fictional prices must be non-negative')
    return requests*amounts[0]+amounts[1]+amounts[2]

if __name__=='__main__':
    print(json.dumps(dict(evaluation={t:evaluate(SCORES,t) for t in ['0.75','0.5','0.4']},permissions=[dict(actor=a,action=k,order=o,allowed=permitted(a,k,o)) for a,k,o in [('alice','view','O1'),('alice','view','O2'),('worker','approve','O1'),('manager','approve','O1'),('unknown','view','O1')]],fictional_cloud_units=fictional_cloud_cost(1000)),default=str,indent=2))
