import requests, io, sys, uuid, zipfile, hashlib, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

API_KEY = 'AIzaSyDY5iRvnRAJJBnVfG7M9JAQqejk2E_US7w'
APP_ID = '1:211370858038:android:c1d7b87ada50fc2446aa97'

r = requests.post('https://firebaseinstallations.googleapis.com/v1/projects/-/installations',
    headers={'X-Goog-Api-Key': API_KEY, 'Content-Type': 'application/json',
             'X-Android-Package': 'com.vinfast.companion.app',
             'X-Android-Cert': None},  # sẽ thay sau
    json={'appId': APP_ID, 'authVersion': 'FIS_v2', 'sdkVersion': 'a:22.3.0',
          'osVersion': '34', 'deviceId': str(uuid.uuid4()).replace('-', '')}, timeout=30)
print('[FIS]', r.status_code, 'body:', r.text[:300])

# X-Android-Cert phải là SHA1 hex của signing cert. Trích cert từ APK:
z = zipfile.ZipFile(r'E:\ios\vf_apk\com.vinfast.companion.app.apk')
certs = [n for n in z.namelist() if n.startswith('META-INF/') and n.upper().endswith(('.RSA', '.DSA', '.EC'))]
print('cert files:', certs)
raw = z.read(certs[0])
# tìm cert inside PKCS#7: pattern seq 30 82 ...4C? — dùng openssl via curl? python không có openssl CLI... dùng hashlib trên DER từ bytes tìm marker
idx = raw.find(b'\x30\x82')  # SEQUENCE bắt đầu cert
# đơn giản: dùng openssl nếu có
import subprocess, os
p = subprocess.run(['openssl', 'pkcs7', '-inform', 'DER', '-in', '-', '-print_certs', '-out', '-'],
                   input=raw, capture_output=True)
if p.returncode != 0:
    print('openssl missing? err=', p.stderr[:200])
else:
    m = re.search(rb'-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----', p.stdout, re.S)
    if m:
        import base64
        der = base64.b64decode(m.group(1).decode())
        sha1 = hashlib.sha1(der).hexdigest().upper()
        print('SHA1(cert) =', sha1)
        r2 = requests.post('https://firebaseinstallations.googleapis.com/v1/projects/-/installations',
            headers={'X-Goog-Api-Key': API_KEY, 'Content-Type': 'application/json',
                     'X-Android-Package': 'com.vinfast.companion.app',
                     'X-Android-Cert': sha1},
            json={'appId': APP_ID, 'authVersion': 'FIS_v2', 'sdkVersion': 'a:22.3.0',
                  'osVersion': '34', 'deviceId': str(uuid.uuid4()).replace('-', '')}, timeout=30)
        print('[FIS+cert]', r2.status_code, r2.text[:300])
