"""Synthetic teaching fixtures; Python 3.10+, standard library only. No network."""
import json, math, re
from collections import Counter
from statistics import mean

def numbers(values):
    if not values or any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in values):
        raise ValueError('Require a nonempty finite numeric sequence')
    return list(values)

def fit_line(xs,ys):
    xs,ys=numbers(xs),numbers(ys)
    if len(xs)!=len(ys):raise ValueError('Length mismatch')
    mx,my=mean(xs),mean(ys);den=sum((x-mx)**2 for x in xs)
    if den==0:raise ValueError('No variation in x')
    slope=sum((x-mx)*(y-my) for x,y in zip(xs,ys))/den
    return {'intercept':my-slope*mx,'slope':slope}

def mae(actual,predicted):
    a,p=numbers(actual),numbers(predicted)
    if len(a)!=len(p):raise ValueError('Length mismatch')
    return mean(abs(x-y) for x,y in zip(a,p))

def labels(values):
    if not values or any(type(v) is not int or v not in (0,1) for v in values):raise ValueError('Binary integer labels required')
    return list(values)

def majority_fit(y):
    y=labels(y)
    # Explicit tie rule: class 0 wins. Training labels only.
    return int(sum(y)>len(y)/2)

def evaluate(actual,predicted,fn_cost=10,fp_cost=2):
    a,p=labels(actual),labels(predicted)
    if len(a)!=len(p):raise ValueError('Length mismatch')
    costs=numbers([fn_cost,fp_cost])
    if min(costs)<0:raise ValueError('Negative cost')
    tp=sum(x==1 and y==1 for x,y in zip(a,p));tn=sum(x==0 and y==0 for x,y in zip(a,p))
    fp=sum(x==0 and y==1 for x,y in zip(a,p));fn=sum(x==1 and y==0 for x,y in zip(a,p))
    return {'tp':tp,'tn':tn,'fp':fp,'fn':fn,'precision':tp/(tp+fp) if tp+fp else None,
            'recall':tp/(tp+fn) if tp+fn else None,'accuracy':(tp+tn)/len(a),'cost':fn*fn_cost+fp*fp_cost}

def monitor(actual,predicted,limit):
    a,p=numbers(actual),numbers(predicted);numbers([limit])
    if limit<0:raise ValueError('Negative limit')
    error=mae(a,p)
    return {'mae':error,'mean_error_actual_minus_prediction':mean(x-y for x,y in zip(a,p)),
            'review_required':error>limit,'limit':limit}

STOP={'the','a','and','is','to','my'}
def tokens(text):
    if not isinstance(text,str):raise ValueError('Text required')
    # English ASCII baseline, not a multilingual tokenizer.
    return [w for w in re.findall(r'[a-z]+',text.lower()) if w not in STOP]

def keywords(text,n=3):
    if type(n) is not int or n<1:raise ValueError('Positive integer n required')
    return sorted(Counter(tokens(text)).items(),key=lambda x:(-x[1],x[0]))[:n]

def text_fit(rows):
    if not rows:raise ValueError('Training rows required')
    counts={0:Counter(),1:Counter()};docs=Counter();vocab=set()
    for text,label in rows:
        labels([label]);words=tokens(text);docs[label]+=1;counts[label].update(words);vocab.update(words)
    if not all(docs[c] for c in (0,1)) or not vocab:raise ValueError('Both classes and vocabulary required')
    return counts,docs,vocab

def text_predict(model,text):
    counts,docs,vocab=model;words=[w for w in tokens(text) if w in vocab]
    scores={c:math.log(docs[c]/sum(docs.values()))+sum(math.log((counts[c][w]+1)/(sum(counts[c].values())+len(vocab))) for w in words) for c in (0,1)}
    return int(scores[1]>scores[0]) # deterministic tie -> 0

def prompt_check(response,expected_id):
    # Mechanical JSON contract, not a semantic/factual safety evaluation.
    if not isinstance(response,str) or not isinstance(expected_id,str):raise ValueError('Strings required')
    try:obj=json.loads(response)
    except (ValueError,TypeError):return {'valid':False,'reason':'invalid JSON'}
    if not isinstance(obj,dict) or set(obj)!={'order_id','action'}:return {'valid':False,'reason':'wrong schema'}
    if obj['order_id']!=expected_id or obj['action'] not in ('review','escalate'):
        return {'valid':False,'reason':'wrong identifier or action'}
    return {'valid':True,'reason':'mechanical contract passed; semantic review still required'}

def demo():
    model=fit_line([1,2,3],[3,5,7]);prediction=[model['intercept']+model['slope']*x for x in [4,5]]
    baseline=majority_fit([0,0,0,1,1]);test=[0,1,1,0]
    tm=text_fit([('late broken parcel',1),('late delivery',1),('thanks excellent service',0),('excellent support thanks',0)])
    return {'regression':{'model':model,'test_predictions':prediction,'test_mae':mae([9,12],prediction)},
            'majority':{'class':baseline,'test_accuracy':evaluate(test,[baseline]*4)['accuracy']},
            'classification':evaluate([1,1,0,0],[1,0,1,0]),
            'monitoring':monitor([100,120,80],[90,100,90],10),
            'keywords':keywords('The late parcel and late refund. Refund is pending.'),
            'text':{'predictions':[text_predict(tm,t) for t in ['late parcel','excellent thanks']], 'unseen_only_class':text_predict(tm,'unseen vocabulary')},
            'prompt':prompt_check('{"order_id":"O1","action":"review"}','O1')}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
