"""Whitelist synthetic thread protocol fields; never publish the raw provider log."""
import json
import pathlib
import re
import sys
records = []
for line in pathlib.Path(sys.argv[1]).open():
    if 'NTIVE: ' not in line:
        continue
    event = json.loads(line.split('NTIVE: ', 1)[1])['event']
    records.append((line[1:25], event['direction'], event['payload']))
thread = next(q['params']['threadId'] for _, direction, q in reversed(records)
              if direction == 'outgoing' and q.get('method') in ('turn/start', 'review/start'))
ids = set()
output = []
for time, direction, q in records:
    p = q.get('params', {})
    item = p.get('item', {})
    row = None
    if direction == 'outgoing' and p.get('threadId') == thread and q.get('method') in ('turn/start', 'review/start', 'turn/interrupt'):
        ids.add(q['id'])
        row = {'method': q['method'], 'requestId': q['id']}
        if q['method'] == 'review/start':
            row.update(target=p['target'], delivery=p['delivery'])
        elif q['method'] == 'turn/start':
            row['input'] = [i['text'] for i in p['input'] if i.get('type') == 'text']
            row['approvalPolicy'] = p.get('approvalPolicy')
            row['sandboxPolicy'] = p.get('sandboxPolicy')
    elif direction == 'incoming' and q.get('id') in ids:
        row = {'requestId': q['id'], 'success': 'result' in q}
        if 'result' in q:
            row['turnStatus'] = q['result'].get('turn', {}).get('status')
    elif p.get('threadId') == thread and q.get('method') == 'item/completed' and item.get('type') in ('enteredReviewMode', 'exitedReviewMode'):
        row = {'method': q['method'], 'itemType': item['type'],
               'review': re.sub(r'/tmp/[^\s`<>]*?/review-demo/', '[synthetic workspace]/', item['review'])}
    elif p.get('threadId') == thread and q.get('method') == 'turn/completed':
        row = {'method': q['method'], 'status': p['turn']['status']}
    if row is not None:
        output.append({'time': time, 'direction': direction, **row})
pathlib.Path(sys.argv[2]).write_text(json.dumps(output, indent=2) + '\n')
print(json.dumps(output, indent=2))
