#!/usr/bin/env python3
"""Unordered SQL representative membership is separate from exact timestamp JSON contract."""
import datetime
import hashlib
import json
import pathlib
import re
import sys

def seconds(value):
    if not isinstance(value,str):
        return value
    match=re.fullmatch(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\.0{1,6}',value)
    if not match:
        return value
    try:
        datetime.datetime.strptime(match[1],'%Y-%m-%d %H:%M:%S')
    except ValueError:
        return value
    return match[1] if int(value[:4])>=1000 else value

def validate(root,prefix=''):
    root=pathlib.Path(root)
    sources=json.loads((root/(prefix+'source-private.json')).read_bytes())
    responses=json.loads((root/(prefix+'responses-private.json')).read_bytes())
    name='STAFF_DINING_ALL'
    source=sources[name]['before']
    response=responses[name]
    wire=response['raw_wire'].encode()
    assert hashlib.sha256(wire).hexdigest()==response['wire_sha256']
    body=json.loads(wire)
    details=[]
    for row in body['data']['rows']:
        menu=source['source_sets']['menus'][row['uuid']]
        times=row['meal_times']
        assert isinstance(times,dict)
        for meal,value in times.items():
            candidates=[item['create_time'] for item in menu if str(item['meal_times'])==str(meal)]
            assert candidates
            details.append({'meal':str(meal),'candidate_count':len(candidates),
                'raw_member':value in candidates,'canonical_member':value in [seconds(x) for x in candidates],
                'value_type':type(value).__name__,'value_bytes':len(value.encode()),
                'mysql_timestamp0_format':type(value) is str and len(value)==19 and seconds(value)==value})
    assert details
    return {'wire_sha256':response['wire_sha256'],'groups':details,
        'actual_representatives_source_members':all(x['raw_member'] or x['canonical_member'] for x in details),
        'mysql_timestamp0_format_pass':all(x['mysql_timestamp0_format'] for x in details),
        'group_representative_selection_semantics':'unspecified SQL GROUP BY column; do not impose MAX',
        'whole_natural_cross_engine_value_equality_claimed':False,'database_operations':0}

if __name__=='__main__':
    print(json.dumps(validate(sys.argv[1],sys.argv[2] if len(sys.argv)>2 else ''),indent=2))
