"""Static disk inspection only. Never executes or attaches to the supplied toolbox."""
import argparse
import hashlib
import json
import re
from pathlib import Path

import pefile


def inspect(path):
    data = path.read_bytes()
    pe = pefile.PE(data=data, fast_load=True)
    pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_IMPORT"]])
    imports = [{"dll": block.dll.decode("ascii", "replace"), "name": item.name.decode("ascii", "replace")}
               for block in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []) for item in block.imports if item.name]
    terms = ["EliteDangerous", "ReturnToMenu", "MainMenu", "Relog", "ReLogin", "RestartGame", "RestartElite", "ExitGame", "KillGame", "QuitGame", "SendInput", "keybd_event", "WriteProcessMemory", "ReadProcessMemory", "CreateRemoteThread", "VirtualAllocEx", "LoadLibrary", "dbghelp", "steam://", "ReloadGame", "hook", "RhInitialize", "NativeAOT"]
    matches = {t: [] for t in terms}
    for match in re.finditer(rb"[ -~]{5,}", data):
        value = match.group().decode("ascii")
        for term in terms:
            if term.lower() in value.lower() and len(matches[term]) < 18:
                matches[term].append({"offset": match.start(), "value": value[:240]})
    chinese = {}
    for text in ["重进", "重登", "主菜单", "大退", "重启", "退出游戏", "汉化", "回到主菜单"]:
        found = []
        for encoding in ["utf-8", "utf-16-le"]:
            needle = text.encode(encoding)
            for m in list(re.finditer(re.escape(needle), data))[:12]:
                found.append({"offset": m.start(), "encoding": encoding})
        chinese[text] = found
    return {"path": str(path), "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data),
            "managedHeaderRva": pe.OPTIONAL_HEADER.DATA_DIRECTORY[14].VirtualAddress,
            "sections": [s.Name.decode("ascii", "replace").strip(chr(0)) for s in pe.sections],
            "imports": imports, "strings": matches, "chineseMarkers": chinese,
            "limits": "Imports/strings establish capabilities and leads, not executed behavior or a publisher exemption."}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("image", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    report = inspect(args.image)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"sha256": report["sha256"], "managedHeaderRva": report["managedHeaderRva"],
                      "strings": report["strings"], "chineseMarkers": report["chineseMarkers"]}, ensure_ascii=False, indent=2))
