#!/usr/bin/env python3
"""Read-only synthetic CSV verifier. Usage: python3 workspace-sales-audit.py FILE.csv"""
import argparse,csv,datetime,hashlib,json,re,time
from decimal import Decimal
from pathlib import Path

def audit(path):
 start=time.perf_counter(); raw=path.read_bytes()
 counts=dict(rows=0,duplicate_excess=0,missing_ids=0,invalid_amounts=0,invalid_dates=0,blank_currencies=0,valid_before_dedup=0,valid_after_dedup=0)
 seen_all=set();seen_clean=set();total=clean=0
 with path.open(newline='',encoding='utf-8-sig') as f:
  reader=csv.DictReader(f)
  required={'deal_id','amount_usd','expected_close','currency'}
  if not required.issubset(reader.fieldnames or []):raise ValueError('Required headers missing: '+', '.join(sorted(required-set(reader.fieldnames or []))))
  for row in reader:
   counts['rows']+=1; ident=row['deal_id'].strip(); amount=row['amount_usd'].strip(); currency=row['currency'].strip()
   if not ident:counts['missing_ids']+=1
   elif ident in seen_all:counts['duplicate_excess']+=1
   else:seen_all.add(ident)
   cents=int(Decimal(amount)*100) if re.fullmatch(r'[+-]?\d+(?:\.\d{1,2})?',amount) else None
   if cents is None:counts['invalid_amounts']+=1
   else:total+=cents
   datestr=row['expected_close'].strip()
   try:
    if not re.fullmatch(r'\d{4}-\d{2}-\d{2}',datestr):raise ValueError('not ISO')
    datetime.date.fromisoformat(datestr);dateok=True
   except ValueError:dateok=False;counts['invalid_dates']+=1
   if not currency:counts['blank_currencies']+=1
   if ident and cents is not None and dateok and currency=='USD':
    counts['valid_before_dedup']+=1
    if ident not in seen_clean:seen_clean.add(ident);counts['valid_after_dedup']+=1;clean+=cents
 return dict(bytes=len(raw),sha256=hashlib.sha256(raw).hexdigest(),**counts,all_parseable_amount_cents=total,cleaned_amount_cents=clean,analysis_seconds=round(time.perf_counter()-start,6),method='Local read-only full CSV parse; no network, connector calls, edits or email; retain first qualifying physical row per ID')
if __name__=='__main__':
 parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('csv',type=Path);args=parser.parse_args();print(json.dumps(audit(args.csv),indent=2))
