"""Find System.exit(10) / killProcess callers and nearby strings in TNG DEX."""
import re
import zipfile
from pathlib import Path

apk = Path(r"C:\Users\Administrator\Desktop\notiMessage\reverse\apks\tng\base.apk")

with zipfile.ZipFile(apk) as z:
    dex_blobs = [(n, z.read(n)) for n in z.namelist() if n.endswith(".dex")]

needles = [
    b"finishAllActivityAndKillApp",
    b"UnhandledEvent detected",
    b"AppSecurityManager: UnhandledEvent",
    b"openSecurityUrl",
    b"startForceExitCountdown",
    b"ForceExitCountdown",
    b"killProcess",
    b"SecurityForceExit",
    b"handleExitApplication",
    b"exitApplication",
    b"Jailbroken/Rooted",
    b"Detected by AppProtect",
]

print("=== string hits ===")
for name, data in dex_blobs:
    for n in needles:
        c = data.count(n)
        if c:
            print(f"{name}: {n.decode(errors='ignore')} x{c}")

# Find UTF-16 / UTF-8 contexts around exit-related
print("\n=== contexts near 'exit' security strings ===")
for name, data in dex_blobs:
    for m in re.finditer(rb"[\x20-\x7e]{0,30}(exit|KillApp|killApp|ForceExit|Unhandled)[\x20-\x7e]{0,80}", data):
        s = m.group().decode("ascii", "ignore")
        if any(k in s.lower() for k in ("force", "kill", "unhandled", "security", "promon", "root")):
            print(f"{name}: {s}")

# Smali-ish type refs
print("\n=== type refs ===")
patterns = [
    rb"Lmy/com/tngdigital/common/internal/_ContextKt;",
    rb"Lmy/com/tngdigital/common/security/model/UnhandledEvent;",
    rb"Lxwwqazamx/W;",
    rb"Lxwwqazamx/bl;",
    rb"Landroid/os/Process;->killProcess",
    rb"Ljava/lang/System;->exit",
    rb"Ljava/lang/Runtime;->exit",
]
for name, data in dex_blobs:
    for pat in patterns:
        hits = len(re.findall(pat, data))
        if hits:
            print(f"{name}: {pat.decode(errors='ignore')} x{hits}")

# Look for const/16 near exit - hard in raw dex; instead find methods that mention exit code strings
print("\n=== classes near ForceExit / KillApp strings ===")
for name, data in dex_blobs:
    for pat in [b"finishAllActivityAndKillApp", b"UnhandledEvent detected", b"startForceExitCountdownIfNeeded"]:
        i = 0
        while True:
            j = data.find(pat, i)
            if j < 0:
                break
            # scan backwards for L...; class descriptor within 2KB
            window = data[max(0, j - 2048):j]
            classes = re.findall(rb"L[\w/$]+;", window)
            if classes:
                print(f"{name} @{j} near {pat.decode()}: ...{classes[-5:]}")
            i = j + 1
