"""Four synthetic CSV exercises. Standard library only; no live business records."""
import csv
from fractions import Fraction
from pathlib import Path

ROOT = Path(__file__).resolve().parent

def read_rows(path, fields, identifier):
    with Path(path).open(newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        if reader.fieldnames != fields:
            raise ValueError('Expected exact ordered headers: ' + ','.join(fields))
        rows = list(reader)
    if not rows:
        raise ValueError('Dataset must contain observations')
    seen = set()
    for row in rows:
        if None in row or any(v is None or not v.strip() for v in row.values()):
            raise ValueError('Missing or extra fields')
        key = row[identifier].strip()
        if key in seen:
            raise ValueError('Repeated observation identifier: ' + key)
        seen.add(key)
    return rows

def flag(value):
    if value not in ('0','1'):
        raise ValueError('Flags must be the strings 0 or 1')
    return int(value)

def number(value):
    if not isinstance(value, (str,int,Fraction)) or isinstance(value,bool):
        raise ValueError('Use a decimal string, integer or Fraction')
    try:
        n = Fraction(value)
    except (ValueError,ZeroDivisionError):
        raise ValueError('Need a finite rational number') from None
    if n < 0:
        raise ValueError('This fixture requires nonnegative values')
    return n

def funnel(path):
    rows = read_rows(path,['lead_id','contacted','quoted','ordered'],'lead_id')
    totals = [len(rows),0,0,0]
    for row in rows:
        contacted,quoted,ordered = [flag(row[k]) for k in ['contacted','quoted','ordered']]
        if not ordered <= quoted <= contacted:
            raise ValueError('This closed nested funnel requires prior stages')
        for i,n in enumerate([contacted,quoted,ordered],1):totals[i] += n
    # An unavailable rate has no invented zero denominator result.
    steps = [Fraction(totals[i+1],totals[i]) if totals[i] else None for i in range(3)]
    return {'counts':totals,'step_rates':steps,'overall':Fraction(totals[3],totals[0])}

def retention(path):
    rows = read_rows(path,['customer_id','baseline_active','later_active'],'customer_id')
    baseline=retained=later=new=0
    for row in rows:
        b,l = flag(row['baseline_active']),flag(row['later_active'])
        baseline += b;retained += b*l;later += l;new += (1-b)*l
    if not baseline:
        raise ValueError('No baseline cohort denominator')
    return {'baseline':baseline,'retained':retained,'later_active':later,'new_later':new,'cohort_rate':Fraction(retained,baseline)}

def forecasts(path):
    rows=read_rows(path,['period','actual','baseline','candidate'],'period')
    errors={'baseline':[],'candidate':[]}
    for row in rows:
        actual=number(row['actual'])
        for name in errors:errors[name].append(number(row[name])-actual)
    return {name:{'mae':sum(map(abs,values),Fraction(0))/len(values),'mean_error':sum(values,Fraction(0))/len(values)} for name,values in errors.items()}

def suppliers(path,quality_weight='0.6',delivery_weight='0.4'):
    qw,dw = number(quality_weight),number(delivery_weight)
    if qw+dw != 1:
        raise ValueError('Weights must sum exactly to one')
    rows=read_rows(path,['supplier_id','quality','delivery'],'supplier_id');result=[]
    for row in rows:
        q,d=number(row['quality']),number(row['delivery'])
        if q>100 or d>100:raise ValueError('Scores must be between 0 and 100; higher is better')
        result.append((row['supplier_id'],q*qw+d*dw))
    return sorted(result,key=lambda x:(-x[1],x[0])) # ID ordering breaks display ties only.

if __name__=='__main__':
    print('Funnel:',funnel(ROOT/'practice_funnel.csv'))
    print('Retention:',retention(ROOT/'practice_retention.csv'))
    print('Forecasts:',forecasts(ROOT/'practice_forecasts.csv'))
    print('Suppliers 0.6/0.4:',suppliers(ROOT/'practice_suppliers.csv'))
    print('Suppliers 0.8/0.2:',suppliers(ROOT/'practice_suppliers.csv','0.8','0.2'))
