"""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_project(source,out):
 # Rebuild independently at order grain, retaining line grain for reconciliation.
 detail=sales(source);by_order=collections.defaultdict(int);by_month=collections.defaultdict(int)
 for r in detail:by_order[r['order_id']]+=r['value_cents'];by_month[r['order_date'][:7]]+=r['value_cents']
 assert len({r['line_id'] for r in detail})==len(detail)
 assert sum(by_order.values())==sum(by_month.values())
 return {'orders':len(by_order),'lines':len(detail),'cents':sum(by_order.values()),'monthly_cents':dict(by_month),'source_hashes':{n:hashlib.sha256((Path(source)/n).read_bytes()).hexdigest() for n in ['orders.csv','order_lines.csv','products.csv']},'claim':'No growth effect or complete accounting revenue claim.'}

def career_evidence(source,out):
 base=py_project(source,out)
 return {'project_claim':'Implemented an analysis of fictional Haven Workshop orders with reconciled line and order grain.','evidence':base,'avoid_claims':['client delivery','employment outcome','accreditation','causal sales improvement'],'independent_extension':'Compare region-level order counts and value, retaining cancelled-order exclusions.'}

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