"""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 bi_measures(source,out):
 data=sales(source);groups={}
 for month in ['2026-04','2026-05','2026-06']:
  subset=[r for r in data if r['order_date'].startswith(month)]
  n=len({r['order_id'] for r in subset});value=sum(r['value_cents'] for r in subset)
  groups[month]={'completed_orders':n,'line_value_eur':value/100 if subset else None,'average_order_eur':value/n/100 if n else None,'coverage':'available' if subset else 'no source coverage'}
 return {'months':groups,'grand_average_eur':1190/21,'arithmetic_mean_of_monthly_aov':(600/11+590/10)/2,'warning':'Grand AOV must use grand value/grand orders, not mean of monthly averages.'}

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=bi_measures(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))
