# -*- coding: utf-8 -*-
"""Quick DEX scan for MariBank SG detection / auth strings."""
import re
import sys
import zipfile
from pathlib import Path

APK = Path(__file__).resolve().parent.parent / "apks" / "maribank_sg_base.apk"
if len(sys.argv) > 1:
    APK = Path(sys.argv[1])

needles = [
    b"ADB",
    b"Wireless ADB",
    b"USB debugging",
    b"Wireless debugging",
    b"Does not support root",
    b"root device",
    b"rooted",
    b"jailbroken",
    b"safemode",
    b"SafeMode",
    b"shpssdk",
    b"SHPSSDK",
    b"getRiskToken",
    b"requestDefense",
    b"BkeApplication",
    b"errorcodehandler",
    b"4067012",
    b"4067004",
    b"/uapi/",
    b"/dfp/",
    b"register",
    b"login",
    b"auth/precheck",
]

class_needles = [
    rb"Lcom/shopee/bke/[\w$/]+;",
    rb"Lcom/shopee/shpssdk[\w$/]*;",
]

with zipfile.ZipFile(str(APK)) as zf:
    data = b"".join(zf.read(n) for n in zf.namelist() if n.endswith(".dex"))
    print("APK:", APK.name, "dex bytes:", len(data))
    print("\n=== string hits ===")
    for n in needles:
        c = data.count(n)
        if c:
            print(f"  {n.decode(errors='replace')!r}: {c}")

    print("\n=== api paths (sample) ===")
    paths = sorted(set(m.group().decode() for m in re.finditer(rb"/v[0-9]/[a-zA-Z0-9_/-]{4,80}", data)))
    for p in paths:
        pl = p.lower()
        if any(k in pl for k in ("auth", "login", "register", "otp", "dfp", "user", "mobile", "pin")):
            print(" ", p)

    print("\n=== shopee/bke classes (sample) ===")
    classes = sorted(set(m.group().decode() for m in re.finditer(rb"Lcom/shopee/bke/[\w$/]{8,120};", data)))
    keywords = ("safemode", "risk", "adb", "debug", "root", "error", "user", "digitalbank", "Application")
    shown = 0
    for c in classes:
        cl = c.lower()
        if any(k in cl for k in keywords):
            print(" ", c)
            shown += 1
            if shown >= 40:
                break
    print(f"  ... total bke classes: {len(classes)}")

    print("\n=== context: ADB Detected ===")
    idx = data.find(b"ADB")
    while idx >= 0 and idx < len(data):
        chunk = data[max(0, idx - 30) : idx + 80]
        if b"Detect" in chunk or b"debug" in chunk.lower() or b"Wireless" in chunk:
            s = re.sub(rb"[^\x20-\x7e]+", b" ", chunk).decode("ascii", "ignore").strip()
            if len(s) > 20:
                print(" ", s[:120])
        idx = data.find(b"ADB", idx + 1)
        if idx > 0 and data.find(b"ADB", idx + 1) == -1:
            break
