"""AutoSoft Python learning labs. Standard-library algorithms, local execution.
Sample outputs are educational, not production predictions or financial advice.
"""
import csv, io, json, math, random, heapq, statistics

def dataset(text):
    if not text.strip():
        rng = random.Random(42)
        return [(float(x), 3*x + 12 + rng.gauss(0, 12)) for x in range(1, 81)]
    rows = list(csv.reader(io.StringIO(text)))
    if not rows or len(rows) > 1001:
        raise ValueError('Use at most 1,000 rows with numeric x,y columns.')
    if [c.strip().lower() for c in rows[0]] == ['x', 'y']:
        rows = rows[1:]
    points = []
    for i, row in enumerate(rows, 1):
        if len(row) != 2:
            raise ValueError(f'Row {i}: expected two columns, x and y.')
        try: pair = tuple(float(v) for v in row)
        except ValueError: raise ValueError(f'Row {i}: both values must be numbers.')
        if not all(math.isfinite(v) and abs(v) <= 1e6 for v in pair):
            raise ValueError('Values must be finite and between -1,000,000 and 1,000,000.')
        points.append(pair)
    if len(points) < 10: raise ValueError('Use at least 10 numeric rows.')
    return points

def series(name, points, kind='line'):
    return {'name': name, 'points': points, 'kind': kind}

def regression(data):
    points = dataset(data.get('csv', ''))
    random.Random(42).shuffle(points)
    n = int(len(points)*0.8)
    train, test = points[:n], points[n:]
    mx, my = statistics.mean(x for x,y in train), statistics.mean(y for x,y in train)
    denom = sum((x-mx)**2 for x,y in train)
    if denom == 0: raise ValueError('Training x values need variation.')
    slope = sum((x-mx)*(y-my) for x,y in train)/denom
    intercept = my - slope*mx
    errors = [(y-(slope*x+intercept))**2 for x,y in test]
    avg = statistics.mean(y for x,y in test)
    total = sum((y-avg)**2 for x,y in test)
    r2 = 1-sum(errors)/total if total else None
    limits = [min(x for x,y in points), max(x for x,y in points)]
    return {'stats': {'Training rows':n,'Test rows':len(test),'Test RMSE':round(math.sqrt(statistics.mean(errors)),3),'Test R²':round(r2,4) if r2 is not None else 'Undefined (constant target)','Slope':round(slope,4),'Intercept':round(intercept,4)},'charts':[{'title':'Held-out test points and fitted line','series':[series('Test data',test,'scatter'),series('Prediction',[(x,slope*x+intercept) for x in limits])]}], 'explanation':'Ordinary least squares with a seeded 80/20 split. Metrics use unseen test rows; no claim of real-world accuracy.'}

def clustering(data):
    rng=random.Random(42)
    points=dataset(data['csv']) if data.get('csv','').strip() else [(rng.gauss(cx,1.2),rng.gauss(cy,1.2)) for cx,cy in [(2,3),(8,8),(12,2)] for _ in range(40)]
    k=int(data.get('value',3))
    if not 2<=k<=6: raise ValueError('Choose 2 to 6 clusters.')
    centers=rng.sample(points,k)
    for iteration in range(60):
        groups=[[] for _ in range(k)]
        for p in points:
            i=min(range(k),key=lambda i:sum((p[j]-centers[i][j])**2 for j in [0,1]))
            groups[i].append(p)
        updated=[tuple(statistics.mean(p[j] for p in g) for j in [0,1]) if g else centers[i] for i,g in enumerate(groups)]
        if max(math.dist(a,b) for a,b in zip(centers,updated))<1e-8: break
        centers=updated
    # Reassign once to ensure plotted groups and inertia match final centers.
    groups=[[] for _ in range(k)]
    for p in points: groups[min(range(k),key=lambda i:math.dist(p,centers[i]))].append(p)
    inertia=sum(math.dist(p,centers[i])**2 for i,g in enumerate(groups) for p in g)
    return {'stats':{'Points':len(points),'Clusters':k,'Iterations':iteration+1,'Inertia':round(inertia,3)},'charts':[{'title':'K-means segmentation (raw feature units)','series':[series(f'Cluster {i+1}',g,'scatter') for i,g in enumerate(groups)]+[series('Centroids',centers,'scatter')]}],'explanation':'Seeded Lloyd k-means. Euclidean distance uses raw x/y units; scale your features appropriately. Inertia alone does not establish a useful segmentation.'}

def pathfinding(data):
    size=18; density=int(data.get('value',20))/100
    if not 0<=density<=40: raise ValueError('Obstacle density must be 0–40%.')
    rng=random.Random(42); start=(0,0); goal=(size-1,size-1)
    blocked={(x,y) for x in range(size) for y in range(size) if rng.random()<density}-{start,goal}
    queue=[(0,0,start)]; costs={start:0}; previous={}; expanded=0
    while queue:
        _,cost,p=heapq.heappop(queue)
        if cost!=costs[p]: continue
        expanded+=1
        if p==goal: break
        for q in [(p[0]+1,p[1]),(p[0]-1,p[1]),(p[0],p[1]+1),(p[0],p[1]-1)]:
            if not (0<=q[0]<size and 0<=q[1]<size) or q in blocked: continue
            if cost+1<costs.get(q,float('inf')):
                costs[q]=cost+1;previous[q]=p
                h=abs(q[0]-goal[0])+abs(q[1]-goal[1]);heapq.heappush(queue,(cost+1+h,cost+1,q))
    path=[]
    if goal in costs:
        p=goal;path=[p]
        while p!=start:p=previous[p];path.append(p)
        path.reverse()
    return {'stats':{'Grid':'18 × 18','Blocked cells':len(blocked),'Expanded nodes':expanded,'Path length':len(path)-1 if path else 'No route'},'grid':{'size':size,'blocked':list(blocked),'path':path},'explanation':'A* search with an admissible Manhattan heuristic and four-direction movement. No route is a valid result when obstacles disconnect the endpoints.'}

def signals(data):
    noise=int(data.get('value',20))/100
    if not 0<=noise<=1:raise ValueError('Noise must be 0–100%.')
    n=128; rng=random.Random(42)
    values=[math.sin(2*math.pi*8*t/n)+0.5*math.sin(2*math.pi*20*t/n)+rng.gauss(0,noise) for t in range(n)]
    spectrum=[]
    for k in range(n//2):
        real=sum(v*math.cos(2*math.pi*k*t/n) for t,v in enumerate(values))
        imag=-sum(v*math.sin(2*math.pi*k*t/n) for t,v in enumerate(values))
        spectrum.append((k,2*math.hypot(real,imag)/n))
    peaks=sorted(spectrum[1:],key=lambda p:p[1],reverse=True)[:2]
    return {'stats':{'Samples':n,'Sampling rate':'128 Hz','Strongest peaks':', '.join(f'{x} Hz' for x,y in peaks),'Noise std. dev.':noise},'charts':[{'title':'Sampled signal (time in seconds)','series':[series('Signal',[(t/n,v) for t,v in enumerate(values)])]},{'title':'DFT amplitude spectrum (frequency in Hz)','series':[series('Amplitude',spectrum)]}],'explanation':'A direct discrete Fourier transform of a synthetic 8 Hz + 20 Hz signal. This is DFT, not an optimized FFT; the small fixed sample count keeps the demonstration responsive.'}

def risk(data):
    volatility=int(data.get('value',20))/100
    if not 0.01<=volatility<=0.6: raise ValueError('Volatility must be 1–60%.')
    rng=random.Random(42);steps=60;count=500;initial=100000;mu=0.06;dt=1/steps
    ends=[];curves=[]
    for i in range(count):
        amount=initial;curve=[(0,amount)]
        for t in range(1,steps+1):
            amount*=math.exp((mu-volatility**2/2)*dt+volatility*math.sqrt(dt)*rng.gauss(0,1))
            if i<8:curve.append((t/steps,amount))
        ends.append(amount)
        if i<8:curves.append(series(f'Path {i+1}',curve))
    ends.sort();p5=ends[int(0.05*(count-1))];median=statistics.median(ends)
    return {'stats':{'Simulations':count,'Horizon':'1 year','Initial value':initial,'Median final value':round(median),'5th percentile':round(p5),'95% VaR (loss)':round(max(0,initial-p5))},'charts':[{'title':'Eight sample price paths (time in years)','series':curves}], 'explanation':'Illustrative geometric Brownian motion with fixed 6% annual drift. No market data, correlations, fees or backtesting. Educational model—not investment advice.'}

def run(request):
    functions={'regression':regression,'clustering':clustering,'pathfinding':pathfinding,'signals':signals,'risk':risk}
    if request.get('project') not in functions:raise ValueError('Unknown Python lab.')
    return functions[request['project']](request)
