"""DIMENSION 4 (duplicates), pass 5: EXHAUSTIVE census of readers of the item
model's duplicate field (item+0x10).

WHY EXHAUSTIVE. Pass 2 found the field surfaced as the Scaleform bool
HAS_DUPLICATE at two sites. A bounded search cannot prove that is the only
consumer, and this project has been bitten four times by absence claims from
narrow searches. So: decompile EVERY function in the binary and match text.

MATCHERS (deliberately two independent ones, plus a control):
  M1 "nested +0x10" regex: the idiom every known site uses, an item pointer
     loaded out of a 0x18-byte list node at node+0x10, then dereferenced at
     +0x10.  e.g.  *(longlong *)(*(longlong *)(lVar10 + 0x10) + 0x10)
  M2 "item-shaped struct" heuristic: a function that mentions at least THREE of
     the known item offsets (+0x18 resourceId, +0x50 cardsubtype, +0x5c state,
     +0x8c timesWon, +0x90 loans) AND also mentions "+ 0x10".
  CONTROL: the three sites already known by hand MUST appear --
     0x180162880 / 0x18013bd40 / 0x1801293d0 / 0x18013e7f0 (writers) and
     0x180043880 / 0x180094220 (readers). If any is missed, the matcher is
     broken and no absence conclusion may be drawn from this pass.

Output is written incrementally so a timeout still leaves usable results.
"""
import re, traceback, time

OUT = "/tmp/claude-1000/-home-alex-Documents-OpenFUT/8e521ca1-ca3e-4138-bb96-df1744dd1d30/scratchpad/store/dup5_out.txt"

M1 = re.compile(r"\*\(longlong \*\)\(\*\(longlong \*\)\([^;\n]{0,80}?\) \+ 0x10\)")
ITEMOFF = ("+ 0x18)", "+ 0x50)", "+ 0x5c)", "+ 0x8c)", "+ 0x90)")
CONTROLS = [0x180162880, 0x18013BD40, 0x1801293D0, 0x18013E7F0, 0x180043880, 0x180094220]

try:
    fh = open(OUT, "w")
    t0 = time.time()
    funcs = []
    it = fm.getFunctions(True)
    while it.hasNext():
        f = it.next()
        funcs.append(f)
    fh.write("total functions: %d\n" % len(funcs))
    fh.flush()

    m1_hits = []
    m2_hits = []
    n = 0
    for f in funcs:
        n += 1
        ent = int(f.getEntryPoint().getOffset())
        try:
            s = dec(ent, timeout=25)
        except Exception:
            fh.write("DECOMPILE-ERROR %#x\n" % ent)
            continue
        if s.startswith("// decompile failed") or s.startswith("// no function"):
            fh.write("DECOMPILE-FAILED %#x\n" % ent)
            continue
        ms = M1.findall(s)
        if ms:
            m1_hits.append((ent, f.getName(), ms))
        k = sum(1 for o in ITEMOFF if o in s)
        if k >= 3 and "+ 0x10" in s:
            m2_hits.append((ent, f.getName(), k))
        if n % 500 == 0:
            fh.write("... %d/%d  %.0fs  m1=%d m2=%d\n" % (n, len(funcs), time.time() - t0,
                                                          len(m1_hits), len(m2_hits)))
            fh.flush()

    fh.write("\nSWEPT %d functions in %.0fs\n" % (n, time.time() - t0))

    fh.write("\n=== CONTROL CHECK ===\n")
    m1set = set(a for a, _, _ in m1_hits)
    m2set = set(a for a, _, _ in m2_hits)
    for c in CONTROLS:
        fh.write("  %#x  M1=%s  M2=%s\n" % (c, c in m1set, c in m2set))

    fh.write("\n=== M1 hits (nested +0x10 idiom): %d functions ===\n" % len(m1_hits))
    for ent, nm, ms in m1_hits:
        fh.write("  %#x %s : %d match(es)\n" % (ent, nm, len(ms)))
        for m in ms[:12]:
            fh.write("        %s\n" % m)

    fh.write("\n=== M2 hits (item-shaped struct, >=3 known item offsets + 0x10): %d ===\n"
             % len(m2_hits))
    for ent, nm, k in m2_hits:
        fh.write("  %#x %s  (%d/5 offsets)\n" % (ent, nm, k))

    fh.close()
    print("WROTE", OUT)
except Exception:
    traceback.print_exc()
