"""Read files only. This script never opens a process or modifies a game image."""
import argparse
import hashlib
import json
from pathlib import Path

import pefile


def inspect(path: 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 = []
    for entry in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []):
        for item in entry.imports:
            name = item.name.decode("ascii", "replace") if item.name else f"ordinal:{item.ordinal}"
            if any(x.lower() in name.lower() for x in ["debugger", "WinVerifyTrust", "NtQueryInformationProcess", "VirtualProtect"]):
                imports.append({"dll": entry.dll.decode("ascii", "replace"), "name": name})
    markers = {}
    for marker in ["EasyAntiCheat", "BattlEye", "FairFight", "Denuvo", "Xigncode", "nProtect", "anticheat", "anti-cheat"]:
        needle, lower = marker.lower().encode(), data.lower()
        at, contexts = 0, []
        while (at := lower.find(needle, at)) != -1:
            start, end = max(0, at - 48), min(len(data), at + len(needle) + 48)
            contexts.append({"offset": at, "context": "".join(chr(c) if 32 <= c < 127 else "." for c in data[start:end])})
            at += len(needle)
        markers[marker] = contexts
    return {"path": str(path.resolve()), "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data),
            "selectedImports": imports, "asciiMarkers": markers,
            "limits": "Static strings and imports do not establish active anti-cheat logic, server checks, detection thresholds, or absence of anti-cheat."}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("image", type=Path)
    parser.add_argument("--output", required=True, type=Path)
    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({k: report[k] for k in ["sha256", "bytes", "selectedImports", "asciiMarkers"]}, ensure_ascii=False))
