# -*- coding: utf-8 -*-
# Extract internal token từ HAR mới nhất -> ghi data/internal_token.json cho core dùng
import json, io, sys, base64, os, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

HAR = sys.argv[1] if len(sys.argv) > 1 else r'E:\ios\vinfast\logbypasssword.har'
OUT = r'E:\ios\vinfast\vinfast-console\data\internal_token.json'
os.makedirs(os.path.dirname(OUT), exist_ok=True)

d = json.load(open(HAR, encoding='utf-8'))
pad = lambda s: s + '=' * (-len(s) % 4)

best = None
for e in d['log']['entries']:
    for x in e['request']['headers']:
        if x['name'].lower() != 'authorization' or not x['value'].startswith('Bearer '):
            continue
        tok = x['value'][7:].strip()
        try:
            claims = json.loads(base64.urlsafe_b64decode(pad(tok.split('.')[1])))
        except Exception:
            continue
        if 'connected-car' in str(claims.get('iss', '')):
            if not best or claims.get('iat', 0) > best[1].get('iat', 0):
                best = (tok, claims)

if not best:
    print('KHÔNG tìm thấy internal token trong HAR!')
    sys.exit(1)

tok, claims = best
data = {
    'access_token': tok,
    'iat': claims.get('iat'),
    'exp': claims.get('exp'),
    'clientInstanceId': claims.get('clientInstanceId'),
    'sub': claims.get('sub'),
    'saved_at': int(time.time()),
    'source': os.path.basename(HAR),
}
with open(OUT, 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)

remain = (claims.get('exp', 0) - time.time()) / 3600
print(f'✅ ĐÃ LƯU internal token -> {OUT}')
print(f'   user: {claims.get("sub")}')
print(f'   clientInstanceId: {claims.get("clientInstanceId")}')
print(f'   còn hạn: {remain:.1f} giờ (exp {claims.get("exp")})')
