"""Original Lawfare Academy training lab; Python 3 + NumPy.
Install numpy in a virtual environment, then run this file.
The nonlinear synthetic target is intentionally chosen; success here does not
establish performance on real customers, untested populations or future tasks.
"""
import numpy as np

def sigmoid(z):
    return 1/(1+np.exp(-np.clip(z,-40,40)))

def dataset(n, seed):
    rng=np.random.default_rng(seed)
    x=rng.uniform(-1,1,size=(n,2))
    y=((x[:,0]*x[:,1])>0).astype(float).reshape(-1,1)
    return x,y

def binary_loss(probability,y):
    p=np.clip(probability,1e-12,1-1e-12)
    return float(-np.mean(y*np.log(p)+(1-y)*np.log(1-p)))

def fit_linear(x,y,steps=1500,rate=.2):
    w=np.zeros((x.shape[1],1));b=0.
    for _ in range(steps):
        p=sigmoid(x@w+b)
        w-=rate*(x.T@(p-y)/len(x))
        b-=rate*float(np.mean(p-y))
    return w,b

def fit_network(x,y,steps=5000,rate=.15,hidden=12,seed=17):
    rng=np.random.default_rng(seed)
    w1=rng.normal(0,.5,(x.shape[1],hidden));b1=np.zeros((1,hidden))
    w2=rng.normal(0,.5,(hidden,1));b2=np.zeros((1,1))
    losses=[]
    for step in range(steps):
        h=np.tanh(x@w1+b1);p=sigmoid(h@w2+b2)
        dz=(p-y)/len(x)
        dw2=h.T@dz;db2=dz.sum(axis=0,keepdims=True)
        dh=(dz@w2.T)*(1-h*h)
        dw1=x.T@dh;db1=dh.sum(axis=0,keepdims=True)
        # Gradients are computed before any weights are mutated.
        w1-=rate*dw1;b1-=rate*db1;w2-=rate*dw2;b2-=rate*db2
        if step%500==0:losses.append(binary_loss(p,y))
    return (w1,b1,w2,b2),losses

def predict(model,x):
    w1,b1,w2,b2=model
    return sigmoid(np.tanh(x@w1+b1)@w2+b2)

def accuracy(p,y):
    return float(np.mean((p>=.5)==y))

def gradient_check():
    x=np.array([[.2,-.7],[.8,.4]]);y=np.array([[0.],[1.]])
    w=np.array([[.1],[-.3]]);b=.05
    analytic=x.T@(sigmoid(x@w+b)-y)/len(x)
    for i in range(2):
        delta=np.zeros_like(w);delta[i,0]=1e-5
        numeric=(binary_loss(sigmoid(x@(w+delta)+b),y)-binary_loss(sigmoid(x@(w-delta)+b),y))/(2e-5)
        assert abs(numeric-analytic[i,0])<1e-7

def main():
    gradient_check()
    train_x,train_y=dataset(500,11)
    validation_x,validation_y=dataset(200,12)
    test_x,test_y=dataset(500,13)
    # Fixed design chosen before inspecting test outcomes. This is one experiment,
    # not a claim that a single random split estimates all uncertainty.
    model,losses=fit_network(train_x,train_y)
    w,b=fit_linear(train_x,train_y)
    baseline=np.full_like(test_y,float(train_y.mean()))
    results={'baseline_test':accuracy(baseline,test_y),
             'linear_test':accuracy(sigmoid(test_x@w+b),test_y),
             'network_validation':accuracy(predict(model,validation_x),validation_y),
             'network_test':accuracy(predict(model,test_x),test_y)}
    assert losses[-1]<losses[0]
    assert results['network_test']>.85
    assert results['network_test']>results['linear_test']+.15
    # Change the label mechanism while leaving input shapes unchanged.
    shifted_y=(test_x[:,0]>0).astype(float).reshape(-1,1)
    results['changed_mechanism']=accuracy(predict(model,test_x),shifted_y)
    print('PASS: gradient check, fixed data partitions, real training and nonlinear model comparison')
    print(results)

if __name__=='__main__':main()
