"""Runnable instructional laboratories. Fictional data; local tests only.

Run: python implementation_laboratories.py
The HTTP fixture binds to loopback and uses fixed fictional tokens to isolate
authorization tests. It is not a production identity or deployment service.
"""
import csv,io,json,math,heapq,sqlite3,tempfile,pathlib,hashlib,threading,concurrent.futures
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
from urllib.request import Request,urlopen
from urllib.error import HTTPError

def ledger(text):
    seen={};totals={}
    for line,row in enumerate(csv.DictReader(io.StringIO(text)),2):
        if set(row)!={'event_id','customer','cents'}:raise ValueError('CSV columns')
        event=row['event_id'];customer=row['customer'];raw=row['cents']
        if not event or not customer or not raw.lstrip('-').isdigit():raise ValueError(f'Invalid row {line}')
        payload=(customer,int(raw))
        if event in seen:
            if seen[event]!=payload:raise ValueError('Conflicting event identity')
            continue
        seen[event]=payload;totals[customer]=totals.get(customer,0)+payload[1]
    return {'events':len(seen),'customers':totals,'net_cents':sum(totals.values())}

def atomic_report(text,destination):
    # Validate before touching the destination. A temporary file isolates output.
    result=ledger(text);destination=pathlib.Path(destination)
    with tempfile.NamedTemporaryFile('w',dir=destination.parent,delete=False) as f:
        temporary=pathlib.Path(f.name);json.dump(result,f,sort_keys=True)
    temporary.replace(destination)
    return result

def shortest_path(graph,start,target):
    for edges in graph.values():
        if any(not isinstance(w,(int,float)) or not math.isfinite(w) or w<0 for _,w in edges):
            raise ValueError('Finite nonnegative weights required')
    distance={start:0};parent={};frontier=[(0,start)];settled=set()
    while frontier:
        cost,node=heapq.heappop(frontier)
        if node in settled:continue
        settled.add(node)
        if node==target:
            path=[target]
            while path[-1]!=start:path.append(parent[path[-1]])
            return cost,list(reversed(path))
        for neighbor,weight in graph.get(node,[]):
            candidate=cost+weight
            if candidate<distance.get(neighbor,math.inf):
                distance[neighbor]=candidate;parent[neighbor]=node
                heapq.heappush(frontier,(candidate,neighbor))
    return None

def linear_fit(points):
    if len(points)<2:raise ValueError('At least two points')
    n=len(points);sx=sum(x for x,y in points);sy=sum(y for x,y in points)
    sxx=sum(x*x for x,y in points);sxy=sum(x*y for x,y in points)
    denominator=n*sxx-sx*sx
    if denominator==0:raise ValueError('Slope not identified by constant x')
    slope=(n*sxy-sx*sy)/denominator
    intercept=(sy-slope*sx)/n
    return intercept,slope

def mean_square_gradient(points,b,w):
    n=len(points)
    if not n:raise ValueError('Empty sample')
    residuals=[(b+w*x-y,x) for x,y in points]
    return (sum(r*r for r,x in residuals)/n,
            2*sum(r for r,x in residuals)/n,
            2*sum(r*x for r,x in residuals)/n)

def sigmoid(z):
    if z>=0:return 1/(1+math.exp(-z))
    e=math.exp(z);return e/(1+e)

def logistic_loss(rows,b,w):
    return sum(max(b+w*x,0)-(b+w*x)*y+math.log1p(math.exp(-abs(b+w*x))) for x,y in rows)/len(rows)

def train_logistic(rows,steps=500,rate=.2):
    if not rows or any(y not in (0,1) for x,y in rows):raise ValueError('Binary labelled data required')
    b=w=0.
    for _ in range(steps):
        residuals=[(sigmoid(b+w*x)-y,x) for x,y in rows]
        b-=rate*sum(r for r,x in residuals)/len(rows)
        w-=rate*sum(r*x for r,x in residuals)/len(rows)
    return b,w

def setup_orders(path):
    with sqlite3.connect(path) as db:
        db.executescript('''
        CREATE TABLE inventory(id INTEGER PRIMARY KEY,quantity INTEGER CHECK(quantity>=0));
        INSERT INTO inventory VALUES(1,1);
        CREATE TABLE orders(id TEXT PRIMARY KEY,owner TEXT NOT NULL,cents INTEGER NOT NULL);
        ''')

def create_order(path,owner,event,cents):
    if not isinstance(cents,int) or isinstance(cents,bool) or cents<0:raise ValueError('Invalid cents')
    with sqlite3.connect(path,timeout=10) as db:
        db.execute('BEGIN IMMEDIATE')
        old=db.execute('SELECT owner,cents FROM orders WHERE id=?',(event,)).fetchone()
        if old:
            if old!=(owner,cents):raise ValueError('Conflicting request ID')
            return {'id':event,'created':False}
        changed=db.execute('UPDATE inventory SET quantity=quantity-1 WHERE id=1 AND quantity>=1').rowcount
        if changed!=1:raise ValueError('Unavailable')
        db.execute('INSERT INTO orders VALUES(?,?,?)',(event,owner,cents))
        return {'id':event,'created':True}

def order_handler(path):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self,*args):pass
        def respond(self,status,body):
            data=json.dumps(body).encode();self.send_response(status)
            self.send_header('Content-Type','application/json');self.send_header('Cache-Control','private, no-store')
            self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
        def identity(self):
            # Test adapter only: a real service verifies sessions/tokens with its identity provider.
            return {'Bearer test-A':'A','Bearer test-B':'B'}.get(self.headers.get('Authorization'))
        def do_POST(self):
            owner=self.identity()
            if not owner:return self.respond(401,{'error':'Authentication required'})
            if self.path!='/orders':return self.respond(404,{'error':'Not found'})
            try:
                size=int(self.headers.get('Content-Length','0'))
                if size<=0 or size>2048:raise ValueError('Body size')
                body=json.loads(self.rfile.read(size))
                if set(body)!={'id','cents'} or not isinstance(body['id'],str) or not body['id']:raise ValueError('Fields')
                result=create_order(path,owner,body['id'],body['cents']);self.respond(201 if result['created'] else 200,result)
            except (ValueError,TypeError,json.JSONDecodeError) as error:self.respond(409,{'error':str(error)})
        def do_GET(self):
            owner=self.identity()
            if not owner:return self.respond(401,{'error':'Authentication required'})
            if not self.path.startswith('/orders/'):return self.respond(404,{'error':'Not found'})
            with sqlite3.connect(path) as db:
                row=db.execute('SELECT id,cents FROM orders WHERE id=? AND owner=?',(self.path.rsplit('/',1)[1],owner)).fetchone()
            self.respond(200,{'id':row[0],'cents':row[1]}) if row else self.respond(404,{'error':'Not found'})
    return Handler

def fingerprint(payload):return hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(',',':')).encode()).hexdigest()

def setup_actions(workflow,provider):
    with sqlite3.connect(workflow) as db:db.execute('CREATE TABLE actions(id TEXT PRIMARY KEY,hash TEXT,state TEXT,result TEXT)')
    with sqlite3.connect(provider) as db:db.execute('CREATE TABLE effects(id TEXT PRIMARY KEY,hash TEXT,result TEXT)')

def approve(workflow,key,payload):
    digest=fingerprint(payload)
    with sqlite3.connect(workflow) as db:
        old=db.execute('SELECT hash FROM actions WHERE id=?',(key,)).fetchone()
        if old:
            if old[0]!=digest:raise ValueError('Approval payload changed')
            return
        db.execute('INSERT INTO actions VALUES(?,?,?,NULL)',(key,digest,'approved'))

def simulated_provider(provider,key,payload):
    # Separate persistent fixture implements an idempotency contract. No external sends.
    digest=fingerprint(payload)
    with sqlite3.connect(provider) as db:
        db.execute('BEGIN IMMEDIATE')
        old=db.execute('SELECT hash,result FROM effects WHERE id=?',(key,)).fetchone()
        if old:
            if old[0]!=digest:raise ValueError('Provider key conflict')
            return old[1]
        result='simulated-receipt-'+key
        db.execute('INSERT INTO effects VALUES(?,?,?)',(key,digest,result));return result

def execute(workflow,provider,key,payload,crash_after_effect=False):
    with sqlite3.connect(workflow) as db:
        changed=db.execute("UPDATE actions SET state='executing' WHERE id=? AND hash=? AND state='approved'",(key,fingerprint(payload))).rowcount
        if changed!=1:raise ValueError('Not the owner of an approved action')
    result=simulated_provider(provider,key,payload)
    if crash_after_effect:raise RuntimeError('Simulated crash after committed provider effect')
    with sqlite3.connect(workflow) as db:db.execute("UPDATE actions SET state='completed',result=? WHERE id=?",(result,key))
    return result

def reconcile(workflow,provider,key):
    with sqlite3.connect(workflow) as db:action=db.execute('SELECT hash,state FROM actions WHERE id=?',(key,)).fetchone()
    if not action:raise ValueError('Unknown action')
    with sqlite3.connect(provider) as db:effect=db.execute('SELECT hash,result FROM effects WHERE id=?',(key,)).fetchone()
    if not effect:return 'uncertain: no confirmed effect; review before retry'
    if effect[0]!=action[0]:raise ValueError('Provider reconciliation conflict')
    with sqlite3.connect(workflow) as db:db.execute("UPDATE actions SET state='completed',result=? WHERE id=?",(effect[1],key))
    return effect[1]

def selftest():
    sample='event_id,customer,cents\n1,Ada,500\n2,Ada,500\n1,Ada,500\n3,Ada,-200\n'
    assert ledger(sample)=={'events':3,'customers':{'Ada':800},'net_cents':800}
    try:ledger(sample+'1,Ada,700\n');raise AssertionError('Conflict accepted')
    except ValueError:pass
    g={'A':[('B',100),('C',2)],'B':[('D',1)],'C':[('D',2)],'D':[('A',1)]}
    assert shortest_path(g,'A','D')==(4,['A','C','D']);assert shortest_path(g,'A','Z') is None
    assert shortest_path({},'A','A')==(0,['A'])
    try:shortest_path({'A':[('B',-1)]},'A','B');raise AssertionError('Negative accepted')
    except ValueError:pass
    points=[(0,1),(1,3),(2,5)];assert linear_fit(points)==(1,2)
    loss,db,dw=mean_square_gradient(points,0,0)
    assert math.isclose(loss,35/3) and math.isclose(db,-6) and math.isclose(dw,-26/3)
    assert mean_square_gradient(points,-.1*db,-.1*dw)[0]<loss
    rows=[(-1,0),(-2/3,0),(-1/3,0),(1/3,1),(2/3,1),(1,1)]
    b,w=train_logistic(rows);assert logistic_loss(rows,b,w)<logistic_loss(rows,0,0)
    assert all((sigmoid(b+w*x)>=.5)==bool(y) for x,y in rows)
    held=[(-.8,0),(-.2,0),(.2,1),(.8,1)]
    assert all((sigmoid(b+w*x)>=.5)==bool(y) for x,y in held)
    assert all((sigmoid(b+w*x)>=.5)!=bool(1-y) for x,y in held)
    with tempfile.TemporaryDirectory() as directory:
        root=pathlib.Path(directory);report=root/'report.json';report.write_text('previous')
        try:atomic_report(sample+'4,Ada,invalid\n',report);raise AssertionError('Invalid accepted')
        except ValueError:pass
        assert report.read_text()=='previous';atomic_report(sample,report)
        orders=str(root/'orders.db');setup_orders(orders)
        server=ThreadingHTTPServer(('127.0.0.1',0),order_handler(orders));thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
        def request(method,path,token=None,body=None):
            headers={'Content-Type':'application/json'}
            if token:headers['Authorization']='Bearer '+token
            req=Request('http://127.0.0.1:'+str(server.server_port)+path,data=json.dumps(body).encode() if body is not None else None,method=method,headers=headers)
            try:
                with urlopen(req) as response:return response.status,json.load(response),response.headers.get('Cache-Control')
            except HTTPError as error:return error.code,json.load(error),error.headers.get('Cache-Control')
        try:
            assert request('POST','/orders',None,{'id':'x','cents':100})[0]==401
            assert request('POST','/orders','test-A',{'id':'x','cents':100})[0]==201
            assert request('POST','/orders','test-A',{'id':'x','cents':100})[0]==200
            assert request('POST','/orders','test-A',{'id':'x','cents':200})[0]==409
            assert request('GET','/orders/x','test-B')[0]==404
            status,body,cache=request('GET','/orders/x','test-A');assert status==200 and body['cents']==100 and cache=='private, no-store'
            assert request('POST','/orders','test-B',{'id':'y','cents':200})[0]==409
            with sqlite3.connect(orders) as db:assert db.execute('SELECT count(*) FROM orders').fetchone()[0]==1
        finally:server.shutdown();server.server_close();thread.join()
        race=str(root/'race.db');setup_orders(race)
        def compete(event):
            try:return create_order(race,event,event,100)['created']
            except ValueError:return False
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:outcomes=list(pool.map(compete,['race-A','race-B']))
        assert outcomes.count(True)==1
        with sqlite3.connect(race) as db:
            assert db.execute('SELECT count(*) FROM orders').fetchone()[0]==1
            assert db.execute('SELECT quantity FROM inventory').fetchone()[0]==0
        workflow=str(root/'workflow.db');provider=str(root/'provider.db');setup_actions(workflow,provider)
        payload={'recipient':'fictional-A','cents':100};approve(workflow,'op1',payload)
        try:execute(workflow,provider,'op1',payload,True);raise AssertionError('Crash not simulated')
        except RuntimeError:pass
        assert reconcile(workflow,provider,'op1')=='simulated-receipt-op1'
        with sqlite3.connect(provider) as db:assert db.execute('SELECT count(*) FROM effects').fetchone()[0]==1
        try:approve(workflow,'op1',{'recipient':'fictional-B','cents':100});raise AssertionError('Changed approval accepted')
        except ValueError:pass
    print('PASS: ledger, atomic export, weighted paths, least squares, gradients, logistic learning/shift, real loopback HTTP authorization/transactions, and durable action reconciliation.')

if __name__=='__main__':selftest()
