import json, time

OUT = r'E:\ios\vf_traffic.ndjson'

def response(flow):
    if any(x in (flow.request.pretty_url or '').lower() for x in ('.png', '.jpg', '.jpeg', '.gif', '.woff', '.svg')):
        return
    rec = {
        'ts': time.strftime('%H:%M:%S'),
        'method': flow.request.method,
        'url': flow.request.pretty_url,
        'status': flow.response.status_code if flow.response else 0,
        'req_host': flow.request.headers.get('host', ''),
        'req_headers': {k.lower(): v for k, v in flow.request.headers.items()
                        if k.lower() in ('authorization', 'x-service-name', 'x-app-version', 'x-device-platform',
                                         'x-device-identifier', 'x-vin-code', 'x-player-identifier',
                                         'x-hash', 'x-hash-2', 'x-timestamp', 'x-device-family',
                                         'x-device-locale', 'x-device-os-version', 'x-country', 'x-timezone',
                                         'x-imei', 'user-agent', 'content-type')},
        'req_body': (flow.request.get_text() or '')[:3500],
        'res_body': (flow.response.get_text() or '')[:3500] if flow.response else '',
    }
    try:
        with open(OUT, 'a', encoding='utf-8') as f:
            f.write(json.dumps(rec, ensure_ascii=False) + '\n')
    except Exception as e:
        print('LOG-FAIL', e)


def error(flow):
    rec = {
        'ts': time.strftime('%H:%M:%S'),
        'type': 'ERROR',
        'url': getattr(flow, 'request', None) and flow.request.pretty_url or f'connect:{flow._conn and flow._conn.server_conn.address}' if flow else '(unknown)',
        'err': repr(flow.error)[:300] if getattr(flow, 'error', None) else 'unknown',
        'status': 0,
    }
    try:
        with open(OUT, 'a', encoding='utf-8') as f:
            f.write(json.dumps(rec, ensure_ascii=False) + '\n')
    except Exception:
        pass
