"""Synthetic retail cleaning and reconciliation lab. Python standard library only.
No business/customer data is used. Zero quantities and missing prices are rejected.
Negative quantities represent returns at the stated price, a simplified metric rule.
Money is stored as integer paise in SQLite; this is not a full accounting system.
"""
from pathlib import Path
from contextlib import closing
from decimal import Decimal, InvalidOperation
import csv
import sqlite3

def clean_rows(rows):
    seen, accepted, rejected, duplicates = {}, [], [], []
    for row in rows:
        key = row.get('transaction_id', '')
        if not key:
            rejected.append(('missing-id', 'transaction identifier required'))
            continue
        if key in seen:
            if row == seen[key]: duplicates.append(key)
            else: rejected.append((key, 'conflicting duplicate identifier'))
            continue
        try:
            quantity = int(row['quantity'])
            price = Decimal(row['unit_price'])
            scaled = price * 100
            if (not row['order_id'] or not row['product'] or quantity == 0
                    or not price.is_finite() or price < 0
                    or scaled != scaled.to_integral_value()
                    or row['currency'] != 'INR'):
                raise ValueError('invalid fields, zero quantity or unsupported money format')
            price_minor = int(scaled)
        except (KeyError, ValueError, InvalidOperation):
            rejected.append((key, 'invalid quantity, price or required fields'))
            continue
        seen[key] = dict(row)
        accepted.append((key, row['order_id'], row['product'], quantity, price_minor))
    return accepted, rejected, duplicates

def report(accepted):
    with closing(sqlite3.connect(':memory:')) as db:
        with db:
            db.execute('CREATE TABLE lines (transaction_id TEXT PRIMARY KEY, order_id TEXT NOT NULL, product TEXT NOT NULL, quantity INTEGER NOT NULL, unit_price_minor INTEGER NOT NULL)')
            db.executemany('INSERT INTO lines VALUES (?,?,?,?,?)', accepted)
            result = db.execute('SELECT COALESCE(SUM(quantity * unit_price_minor),0), COALESCE(SUM(quantity),0) FROM lines').fetchone()
            products = db.execute('SELECT product, SUM(quantity), SUM(quantity * unit_price_minor) FROM lines GROUP BY product ORDER BY product').fetchall()
    return {'net_value_minor': result[0], 'net_units': result[1], 'products': products}

def main():
    with Path(__file__).with_name('retail_transactions.csv').open(newline='') as f:
        accepted, rejected, duplicates = clean_rows(list(csv.DictReader(f)))
    result = report(accepted)
    print('Accepted lines:', len(accepted))
    print('Duplicate lines:', duplicates)
    print('Rejected lines:', rejected)
    print('Net units:', result['net_units'])
    print('Net transaction value (INR):', Decimal(result['net_value_minor']) / 100)
    for product, units, minor in result['products']:
        print(product, 'net units', units, 'net value INR', Decimal(minor) / 100)
    print('Interpretation: transaction value is not profit; no costs or taxes are modelled.')

if __name__ == '__main__': main()
