# -*- coding: utf-8 -*-
import subprocess
import zipfile
from pathlib import Path

APK = Path(__file__).resolve().parent.parent / "apks" / "maribank_sg_base.apk"
DEXDUMP = Path(r"C:\Users\Administrator\AppData\Local\Android\Sdk\build-tools\37.0.0\dexdump.exe")
TARGETS = [
    "Lcom/shopee/bke/lib/safemode/model/ErrorType;",
    "Lcom/shopee/bke/lib/safemode/activity/SafeModeRecoverActivity;",
    "Lcom/shopee/bke/lib/safemode/b;",
]

with zipfile.ZipFile(str(APK)) as zf:
    for name in zf.namelist():
        if not name.endswith(".dex"):
            continue
        data = zf.read(name)
        if not any(t.replace("L", "").replace(";", "").encode() in data for t in TARGETS):
            continue
        tmp = Path(__file__).resolve().parent.parent / "tmp" / "sg_safemode.dex"
        tmp.parent.mkdir(parents=True, exist_ok=True)
        tmp.write_bytes(data)
        out = subprocess.check_output(
            [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
        )
        for target in TARGETS:
            if target.replace("L", "").replace(";", "") not in data.decode("latin1", errors="ignore"):
                continue
            print("=" * 60, name, target)
            cap = False
            for line in out.splitlines():
                if f"Class descriptor  : '{target}'" in line:
                    cap = True
                elif cap and line.startswith("  Class descriptor") and target not in line:
                    break
                if cap and ("name          :" in line or "const-string" in line or "ErrorType" in line):
                    print(line.strip()[:140])
