"""Local fictional learning reference. No website/database/cloud connection."""
import csv,json,sqlite3,hashlib,math,re,statistics,collections
from pathlib import Path

def rows(source,name):
 with (Path(source)/name).open(encoding='utf-8',newline='') as f:return list(csv.DictReader(f))

def sales(source):
 from datetime import date
 order_rows=rows(source,'orders.csv');line_rows=rows(source,'order_lines.csv');product_rows=rows(source,'products.csv')
 if len({r['order_id'] for r in order_rows})!=len(order_rows) or any(not r['order_id'] for r in order_rows):raise ValueError('Order keys must be unique and nonempty')
 if len({r['product_id'] for r in product_rows})!=len(product_rows):raise ValueError('Product keys must be unique')
 if len({r['line_id'] for r in line_rows})!=len(line_rows):raise ValueError('Line keys must be unique')
 for r in order_rows:
  if r['status'] not in ['completed','cancelled']:raise ValueError('Unknown order status')
  if not re.fullmatch(r'\d{4}-\d{2}-\d{2}',r['order_date']):raise ValueError('ISO calendar date required')
  date.fromisoformat(r['order_date'])
 orders={r['order_id']:r for r in order_rows};products={r['product_id'] for r in product_rows};result=[]
 for r in line_rows:
  if not r['line_id'] or r['order_id'] not in orders or r['product_id'] not in products:raise ValueError('Unmatched or empty business key')
  quantity=int(r['quantity']);price=int(r['unit_price_cents'])
  if quantity<=0 or price<0:raise ValueError('Invalid line numeric domain')
  if orders[r['order_id']]['status']=='completed':result.append(dict(r,quantity=quantity,unit_price_cents=price,value_cents=quantity*price,**orders[r['order_id']]))
 return result

def py_basics(source,out):
 values=sales(source);month={}
 for r in values:
  key=r['order_date'][:7];month[key]=month.get(key,0)+r['value_cents']
 return {'raw_orders':len(rows(source,'orders.csv')),'accepted_lines':len(values),'monthly_cents':month,'grand_cents':sum(month.values()),'average_completed_order_eur':sum(month.values())/21/100}

if __name__=='__main__':
    import argparse,platform
    parser=argparse.ArgumentParser();parser.add_argument('--source',default='.');parser.add_argument('--output',required=True);args=parser.parse_args()
    source=Path(args.source).resolve();out=Path(args.output).resolve()
    if source==out:raise ValueError('Source and output must differ')
    out.mkdir(parents=False,exist_ok=False)
    # Partial folders after an error are NOT successful; result.json is written last.
    result=py_basics(source,out)
    with (out/'result.json').open('x',encoding='utf-8') as handle:json.dump(result,handle,indent=2,allow_nan=False);handle.write(chr(10))
    print(json.dumps(result,indent=2,allow_nan=False))
