"""Six bounded records lessons. Python 3.10+, standard library, synthetic data only."""
import csv
import json
import sqlite3
import statistics
from pathlib import Path

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


def clean_rows(rows):
    """First valid ID wins; identical replay skipped, conflicting replay quarantined."""
    accepted, issues, seen = [], [], {}
    for number, raw in enumerate(rows, 2):
        try:
            if set(raw) != {'order_id', 'customer_id', 'amount_paise'}:
                raise ValueError('columns')
            order_id = raw['order_id'].strip()
            customer_id = raw['customer_id'].strip()
            amount_text = raw['amount_paise'].strip()
            if not order_id or not customer_id:
                raise ValueError('missing identifier')
            if not amount_text.isascii() or not amount_text.isdecimal():
                raise ValueError('amount must be nonnegative integer paise')
            amount = int(amount_text)
            if amount > 9223372036854775807:
                raise ValueError('amount exceeds SQLite integer range')
            record = (order_id, customer_id, amount)
            if order_id in seen:
                reason = 'identical replay' if seen[order_id] == record else 'conflicting replay'
                issues.append({'line': number, 'reason': reason, 'order_id': order_id})
                continue
            seen[order_id] = record
            accepted.append(record)
        except (ValueError, AttributeError, TypeError) as error:
            issues.append({'line': number, 'reason': str(error)})
    return accepted, issues


def read_orders(path=HERE / 'practice_orders.csv'):
    with Path(path).open(newline='', encoding='utf-8') as file:
        reader = csv.DictReader(file)
        if reader.fieldnames != ['order_id', 'customer_id', 'amount_paise']:
            raise ValueError('expected exact order_id,customer_id,amount_paise header')
        return clean_rows(list(reader))


def database():
    db = sqlite3.connect(':memory:')
    db.execute('PRAGMA foreign_keys=ON')
    if db.execute('PRAGMA foreign_keys').fetchone()[0] != 1:
        raise RuntimeError('foreign keys unavailable')
    db.executescript((HERE / 'records_schema.sql').read_text())
    db.executemany('INSERT INTO customers VALUES (?,?)', [('C1','Asha'),('C2','Dev'),('C3','Meera')])
    db.executemany('INSERT INTO orders VALUES (?,?,?)', [('O1','C1',10000),('O2','C1',20000),('O3','C2',30000)])
    db.executemany('INSERT INTO payments VALUES (?,?,?)', [('P1','O1',4000),('P2','O1',6000),('P3','O2',15000),('P4','O3',35000)])
    db.commit()
    return db


def joins(db):
    inflated = db.execute('SELECT SUM(o.amount_paise) FROM orders o JOIN payments p ON p.order_id=o.order_id').fetchone()[0]
    total = db.execute('SELECT SUM(amount_paise) FROM orders').fetchone()[0]
    # COUNT(o.order_id) counts matched orders, unlike COUNT(*) on a left join.
    customers = db.execute('SELECT c.customer_id,COUNT(o.order_id),COALESCE(SUM(o.amount_paise),0) FROM customers c LEFT JOIN orders o ON o.customer_id=c.customer_id GROUP BY c.customer_id ORDER BY c.customer_id').fetchall()
    return {'naive_join_total_paise': inflated, 'order_total_paise': total, 'customer_summary': customers}


def reconciliation(db):
    # Aggregate many payments BEFORE joining them to the one-order grain.
    return db.execute('''WITH paid AS (SELECT order_id,SUM(amount_paise) amount FROM payments GROUP BY order_id)
      SELECT o.order_id,o.amount_paise,COALESCE(p.amount,0),o.amount_paise-COALESCE(p.amount,0)
      FROM orders o LEFT JOIN paid p ON p.order_id=o.order_id ORDER BY o.order_id''').fetchall()


def constraint_demo(db):
    cases = {
        'duplicate key': ('INSERT INTO orders VALUES (?,?,?)', ('O1','C1',10)),
        'unknown customer': ('INSERT INTO orders VALUES (?,?,?)', ('O9','C9',10)),
        'negative amount': ('INSERT INTO orders VALUES (?,?,?)', ('O9','C1',-1)),
        'missing amount': ('INSERT INTO orders VALUES (?,?,?)', ('O9','C1',None)),
        'fractional amount': ('INSERT INTO orders VALUES (?,?,?)', ('O9','C1',1.5)),
        'delete referenced customer': ('DELETE FROM customers WHERE customer_id=?', ('C1',)),
    }
    rejected = []
    for label, (sql, args) in cases.items():
        try:
            with db:
                db.execute(sql,args)
        except sqlite3.IntegrityError:
            rejected.append(label)
        else:
            raise AssertionError('constraint unexpectedly accepted: '+label)
    # A business operation with two inserts must roll back its first insert if second fails.
    try:
        with db:
            db.execute('INSERT INTO orders VALUES (?,?,?)', ('OX','C1',500))
            db.execute('INSERT INTO payments VALUES (?,?,?)', ('PX','missing',500))
    except sqlite3.IntegrityError:
        pass
    rollback = db.execute("SELECT COUNT(*) FROM orders WHERE order_id='OX'").fetchone()[0] == 0
    return {'rejected': rejected, 'transaction_rolled_back': rollback}


def describe(records):
    values = [r[2] for r in records]
    if not values:
        return {'n':0, 'total_paise':0, 'mean_paise':None, 'median_paise':None, 'sample_stdev_paise':None}
    return {'n':len(values), 'total_paise':sum(values), 'mean_paise':statistics.mean(values),
            'median_paise':statistics.median(values), 'sample_stdev_paise':statistics.stdev(values) if len(values)>1 else None}


def quality(records, issues, customer_ids):
    # Valid formatting does not establish referential validity or source truth.
    orphans = [r[0] for r in records if r[1] not in customer_ids]
    return {'accepted_format_rows':len(records), 'issue_rows':len(issues), 'unknown_customer_order_ids':orphans,
            'issues_by_reason':{reason:sum(x['reason']==reason for x in issues) for reason in sorted({x['reason'] for x in issues})},
            'release_ready':not issues and not orphans}


def main():
    records, issues = read_orders()
    with database() as db:
        result = {'joins':joins(db), 'reconciliation':reconciliation(db), 'constraints':constraint_demo(db),
                  'cleaning':{'accepted':records,'issues':issues}, 'statistics':describe(records),
                  'quality':quality(records,issues,{'C1','C2','C3'})}
    db.close()
    print(json.dumps(result,indent=2))

if __name__ == '__main__':
    main()
