#!/usr/bin/env python3
import json,re
from decimal import Decimal
from compare import ROOT,equal
def no_business_write(sql):return not re.match(r'^\s*(insert|update|delete|alter|drop|create|truncate|grant|revoke)\b',sql,re.I)
def audit():
 out={}
 for lane in ('B','C'):
  d=ROOT/'private-evidence'/lane;f=json.loads((d/'fixture-journal.json').read_text());assert f['committed'] and len(f['dml'])==8
  for module,tenant in [('store',2147001111),('terminal',2147001112)]:
   ids=f['owned'][module]
   for table,pk in [('order_delivery','delivery_id'),('order_delivery_goods','id'),('order_refund','order_refund_id'),('order_refund_image','id')]:
    record=next(x for x in f['dml'] if x['table']==table and int(x['values']['store_id'])==tenant);assert pk not in record['values'] and record['generated_PK']==ids[table];row=next(r for r in f['after'][table] if int(r[pk])==ids[table]);assert int(row['store_id'])==tenant
    for k,v in record['values'].items():
     if k=='refund_money':assert Decimal(v)==Decimal('0.00') and Decimal(str(row[k]))==Decimal('0.00')
     elif type(v) is int:assert int(row[k])==v
     else:equal(row[k],v,lane+'.insert_full_column.'+table+'.'+k)
    if table in ('order_delivery','order_delivery_goods','order_refund'):assert int(row['order_id'])==ids['order']
    if table in ('order_delivery_goods','order_refund'):assert int(row['order_goods_id'])==ids['order_goods']
    if table=='order_delivery':assert int(row['delivery_method'])==10 and int(row['express_id'])==0 and row['eorder_html']==''
    if table=='order_delivery_goods':assert int(row['delivery_num'])==0 and int(row['delivery_id'])==ids['order_delivery'] and int(row['goods_id'])==ids['goods']
    if table=='order_refund':assert int(row['user_id'])==ids['user'] and int(row['type'])==20 and int(row['audit_status'])==20 and int(row['status'])==10 and int(row['is_user_send'])==0 and int(row['is_receipt'])==0 and str(row['express_id'])=='0'
    if table=='order_refund_image':assert int(row['image_id'])==ids['upload_file'] and int(row['order_refund_id'])==ids['order_refund']
  for t in ('user','goods','order','order_goods','upload_file','order_address','payment_trade','express','order_refund_address'):equal(f['before'][t],f['after'][t],lane+'.existing_full_rows.'+t)
  equal(f['before_protect'],f['after_protect'],lane+'.natural_new_table_counts')
  counts={'HTTP_business_DML':0,'DDL':0,'fixture_INSERT':8,'fixture_UPDATE':0,'SELECT':0,'metadata':0,'HTTP':0,'original_13_table_sets':0}
  for line in (d/'private-sql.jsonl').read_text().splitlines():
   sql=json.loads(line)['sql'];assert no_business_write(sql),'Unexpected HTTP write '+sql
   if re.match(r'^show\b',sql,re.I) or re.search(r'\bsyscolumns\b|\bsysobjects\b|USER_TAB_COLUMNS|SP_TABLEDEF|USER_CONS_COLUMNS|USER_CONSTRAINTS',sql,re.I):counts['metadata']+=1
   elif re.match(r'^select\b',sql,re.I):counts['SELECT']+=1
  for line in (d/'private-wire.jsonl').read_text().splitlines():
   w=json.loads(line);equal(w['original'],f['after'],w['scenario']+'.unchanged13tables');counts['HTTP']+=1;counts['original_13_table_sets']+=13
  for p in d.glob('run-*.json'):
   r=json.loads(p.read_text());assert r['own_unchanged'] and r['natural_count_unchanged'] and r['cache_cleared']
  out[lane]=counts
 return out
if __name__=='__main__':
 r=audit();(ROOT/'sql-audit.json').write_text(json.dumps(r,indent=2)+'\n');print(json.dumps(r))
