"""Synthetic, single-process teaching pipeline. No external dependencies."""
import csv
import json
import sqlite3
from collections import deque
from contextlib import closing
from pathlib import Path

def validate(raw):
    if not isinstance(raw['id'], str) or not isinstance(raw['department'], str):
        raise ValueError('identifier and department must be text')
    identifier=raw['id'].strip()
    department=raw['department'].strip()
    if not identifier or not department:
        raise ValueError('identifier and department are required')
    quantity=int(raw['quantity']); price=int(raw['unit_paise'])
    if quantity<=0 or price<0:
        raise ValueError('quantity must be positive and price non-negative')
    return (identifier,department,quantity,price)

def process(rows):
    accepted={}; queue=deque(); events=[]
    for position,raw in enumerate(rows,1):
        try:
            item=validate(raw)
        except (KeyError,ValueError,TypeError) as error:
            events.append(dict(row=position,status='rejected',reason=str(error)))
            continue
        key=item[0]
        if key in accepted:
            status='replayed' if accepted[key]==item else 'conflicting'
        else:
            accepted[key]=item;queue.append(key);status='accepted'
        events.append(dict(row=position,id=key,status=status))
    processing_order=[]
    with closing(sqlite3.connect(':memory:')) as db:
        with db:
            db.execute('CREATE TABLE orders (id TEXT PRIMARY KEY, department TEXT NOT NULL, quantity INTEGER NOT NULL CHECK(quantity>0), unit_paise INTEGER NOT NULL CHECK(unit_paise>=0))')
            while queue:
                key=queue.popleft();processing_order.append(key)
                db.execute('INSERT INTO orders VALUES (?,?,?,?)',accepted[key])
            sql_total=db.execute('SELECT COALESCE(SUM(quantity*unit_paise),0) FROM orders').fetchone()[0]
            groups=[dict(department=d,value_paise=v) for d,v in db.execute('SELECT department,SUM(quantity*unit_paise) FROM orders GROUP BY department ORDER BY department')]
    counts={s:sum(e['status']==s for e in events) for s in ['accepted','replayed','conflicting','rejected']}
    python_total=sum(x[2]*x[3] for x in accepted.values())
    if python_total!=sql_total or sum(counts.values())!=len(events):
        raise RuntimeError('reconciliation failed')
    return dict(counts=counts,processing_order=processing_order,value_paise=sql_total,groups=groups,events=events)

def read_fixture(path):
    with Path(path).open(newline='',encoding='utf-8') as handle:
        return list(csv.DictReader(handle))

if __name__=='__main__':
    print(json.dumps(process(read_fixture(Path(__file__).with_name('order_workflow.csv'))),indent=2))
