#!/usr/bin/env python3
"""Validate authored CSV fixtures without database, network, or model calls."""
import csv,json,hashlib,argparse
from pathlib import Path
from datetime import datetime
from collections import Counter,defaultdict
KIND='logistics'
def calculate(p):
 names=['events.csv','documents.csv','metric-contract.json'] if KIND=='logistics' else ['tickets.csv','manual-labels.csv','metric-contract.json']
 def read(name):
  with (p/name).open(newline='') as f:return list(csv.DictReader(f))
 c=json.loads((p/names[2]).read_text());a,b=read(names[0]),read(names[1])
 def unique(rows,key):
  values=[r[key] for r in rows]
  if any(not x for x in values) or len(values)!=len(set(values)):raise ValueError('Missing/duplicate '+key)
 if KIND=='logistics':
  unique(a,'event_id');unique(b,'id')
  def stamp(x):
   d=datetime.fromisoformat(x.replace('Z','+00:00'))
   if d.tzinfo is None or d.utcoffset().total_seconds()!=0:raise ValueError('Explicit UTC required')
   return d
  w=c['window'];start,end,asof=map(stamp,[w['start_inclusive'],w['end_exclusive'],w['data_as_of']])
  if start>=end or w['time_basis']!='occurred_at':raise ValueError('Invalid occurred_at window')
  for r in a:
   if stamp(r['received_at'])<stamp(r['occurred_at']):raise ValueError('Received before occurred')
  eligible=[r for r in a if r['status']=='delivered' and start<=stamp(r['occurred_at'])<end and stamp(r['received_at'])<=asof]
  trips=sorted({r['trip_id'] for r in eligible});alltrips={r['trip_id'] for r in a}
  if any(r['trip_id'] not in alltrips or not r['text'] or int(r['page'])<1 for r in b):raise ValueError('Invalid document reference')
  noted={r['trip_id'] for r in b};result={'events_in_window':len(eligible),'distinct_delivered_trips':len(trips),'trips_with_matching_document':len(set(trips)&noted),'document_review':sorted(set(trips)-noted),'outside_window':sorted({r['trip_id'] for r in a if not start<=stamp(r['occurred_at'])<end})}
  evidence={'included_event_ids':[r['event_id'] for r in eligible],'included_trip_ids':trips,'late_received_event_ids':[r['event_id'] for r in eligible if stamp(r['received_at'])>=end],'excluded_events':[{'event_id':r['event_id'],'reason':'occurred_at_outside_window' if not start<=stamp(r['occurred_at'])<end else 'status_or_as_of_filter'} for r in a if r not in eligible],'missing_document_is_not_undelivered':True}
 else:
  unique(a,'ticket_id');lookup={r['ticket_id']:r for r in a};pairs=[(r['ticket_id'],r['label']) for r in b]
  if len(pairs)!=len(set(pairs)):raise ValueError('Duplicate manual label')
  groups=defaultdict(lambda:{'unique_tickets':0,'issue_mentions':0})
  for r in a:groups[r['service_entity']]['unique_tickets']+=1
  for r in b:
   if r['ticket_id'] not in lookup:raise ValueError('Orphan label')
   t=lookup[r['ticket_id']];s,e=int(r['start_inclusive']),int(r['end_exclusive'])
   if s<0 or e<=s or t['message'][s:e]!=r['quote'] or t['service_entity']!=r['service_entity']:raise ValueError('Evidence span/entity mismatch')
   groups[r['service_entity']]['issue_mentions']+=1
  late={r['ticket_id'] for r in b if r['label']=='late_delivery'}
  result={'unique_tickets':len(a),'issue_mentions':len(b),'late_delivery_tickets':len(late),'late_delivery_share_of_tickets':len(late)/len(a),'late_delivery_share_of_issue_mentions':sum(r['label']=='late_delivery' for r in b)/len(b),'service_entity_groups':dict(groups)}
  evidence={'manual_annotation_only':True,'evidence_spans_verified':len(b),'late_delivery_ticket_ids':sorted(late),'no_prediction_or_root_cause_inference':True}
 if result!=c['expected']:raise ValueError('Expected contract mismatch: '+json.dumps(result))
 return {'calculation':'Python standard-library CSV calculation','not_a_model_result':True,'not_production_data':True,'input_sha256':{n:hashlib.sha256((p/n).read_bytes()).hexdigest() for n in names},'result':result,'evidence':evidence,'validation_passed':True}
if __name__=='__main__':
 parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--source-dir',type=Path,default=Path(__file__).resolve().parent);parser.add_argument('--output',type=Path);args=parser.parse_args();s=json.dumps(calculate(args.source_dir),indent=2)+'\n'
 if args.output:args.output.write_text(s)
 else:print(s,end='')
