# -*- coding: utf-8 -*-
# Parse HAR FaceID login mới: tìm sequence login đầy đủ (grant_type=app + WebAuthn + challenge)
import json, io, sys, base64
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
HAR = r'E:\ios\vinfast\logbypasssword.har'
d = json.load(open(HAR, encoding='utf-8'))
entries = d['log']['entries']
print('TỔNG entries:', len(entries))

def hmap(h):
    return {x['name'].lower(): x['value'] for x in h}

# Hosts overview
hosts = {}
for e in entries:
    u = e['request']['url']
    h = u.split('/')[2] if u.count('/') >= 2 else u
    hosts[h] = hosts.get(h, 0) + 1
print('\n== HOSTS ==')
for h, c in sorted(hosts.items(), key=lambda x: -x[1]):
    print(f'   {h:55s} {c}')

# Chi tiết Auth0 + ccaruaa + auth0/account + bất kỳ endpoint lạ nào
print('\n== CHI TIẾT LOGIN FLOW (auth0 / ccaruaa / account / webauthn / instance) ==')
for e in entries:
    u = e['request']['url']
    low = u.lower()
    if not any(k in low for k in ['auth0.com', 'ccaruaa', 'auth0/account', 'webauthn', 'instance', 'client/credentials']):
        continue
    rq, rs = e['request'], e['response']
    path = '/' + u.split('/', 3)[3] if u.count('/') >= 3 else u
    print(f"\n--- [{rs['status']}] {rq['method']} {path[:130]}")
    h = hmap(rq['headers'])
    for k in ('authorization', 'x-hash', 'x-timestamp'):
        if k in h: print(f'    {k}: {h[k][:80]}')
    pd = rq.get('postData', {})
    body = pd.get('text') or json.dumps(pd.get('params', []), ensure_ascii=False)
    if body: print(f'    BODY: {body[:700]}')
    rtxt = rs.get('content', {}).get('text', '')
    if rtxt:
        try:
            j = json.loads(rtxt)
            def mask(v):
                v = str(v)
                return v[:30] + f'...({len(v)}ch)' if len(v) > 60 else v
            def walk(o, pre='', depth=0):
                if depth > 3: return
                if isinstance(o, dict):
                    for k, v in o.items():
                        if isinstance(v, (dict, list)): walk(v, pre + str(k) + '.', depth + 1)
                        else: print(f'    RSP {pre}{k}: {mask(v)}')
                elif isinstance(o, list):
                    for i, v in enumerate(o[:3]): walk(v, pre + f'[{i}].', depth + 1)
            walk(j)
        except Exception:
            print(f'    RSP(raw): {rtxt[:300]}')
