"""D2 QUICK SELL, batch 3.

ESTABLISHED SO FAR
  * item struct base in FUN_18013fe00 is RBP+0x160 (local_188). Therefore
      item+0x38 = discardValue as SENT BY THE SERVER (atom 0xd7)
      item+0x3c = discardValue COMPUTED LOCALLY, only when item+0x38 == 0
      item+0x4c = cardtype (= FUN_1800d8330(cardsubtypeid))
      item+0x50 = cardsubtypeid, item+0x54 = "level" query key
      item+0x58 = rareflag, item+0xb4 = rating
  * the local formula is round_half_up(rating * price / 100) where
      price = SELECT price FROM fcc_discardcoins
              WHERE cardtype==item+0x4c AND level==item+0x54 AND rare==item+0x58
  * item+0x54 ("level") has EXACTLY ONE reference in the whole function and it is
    a READ; the only write is the 16-byte MOVDQA initialiser at 0x18013ffa1 from
    _DAT_1801f66a0 = 56 01 00 00 | 00 00 00 00 | ... so level is CONSTANT 0.
  * only two functions in the DLL carry the 0x326 (totalCredits) immediate:
    FUN_180127300 (DiscardCard) and FUN_1801279c0 (DiscardCardByRes). Both store
    to obj+0x28 with a plain MOV, never a read-modify-write.

THIS BATCH
  A. who READS obj+0x28 on the DiscardCard server-call object? dump the class
     vtable at 0x180220488 (slot +0x08 == 0x180127300 confirms the base) and
     decompile every slot; likewise the DiscardCardByRes vtable located by
     searching .rdata for the qword 0x1801279c0.
  B. the FUT manager singleton: FUN_18011d780 writes DAT_1802e6398. find the
     concrete vtable, dump slots 0x9c0..0xa90, decompile 0xa08 / 0xa30 / 0xa48
     and every neighbour whose body mentions a credit-looking field.
  C. who reads item+0x38 and item+0x3c? enumerate every function that both
     (i) references the item registration entry point mgr->vt[0xa08] target and
     (ii) contains a +0x38 / +0x3c memory operand. Also print the a08 target.
  D. Q3 bulk discard: resolve the class that owns FUN_180126f40 by searching
     .rdata for that qword, dump its vtable and decompile its url builder and
     response deserialiser, so the bulk request/response shape is read off code.
  E. print the raw .rdata around each RS4 discard literal so the class list is
     visible.

CONTROLS
  * vtable slot +0x08 of 0x180220488 must equal 0x180127300 (already observed).
  * the .rdata qword search must find 0x180127300 at 0x180220490 (already
    observed via xrefs_to) -- same syntactic form as the searches for
    0x1801279c0 and 0x180126f40, so a hit there validates the method.
"""
import traceback, os, struct

OUT = "/tmp/claude-1000/-home-alex-Documents-OpenFUT/8e521ca1-ca3e-4138-bb96-df1744dd1d30/scratchpad/store/qs/"
os.makedirs(OUT, exist_ok=True)


def dump(tag, va, path=None):
    try:
        src = dec(va)
    except Exception as e:
        src = "// decompile threw %r" % (e,)
    print("=" * 78)
    print("%s  %#x  fname=%s  len(src)=%d  (FULL)" % (tag, va, fname(va), len(src)))
    print("=" * 78)
    print(src)
    if path:
        open(OUT + path, "w").write(src)
    return src


def q(a):
    return struct.pack("<Q", a)


try:
    print("##### CONTROL: .rdata qword search #####")
    for tgt in (0x180127300, 0x1801279c0, 0x180126f40, 0x180127570, 0x18013fe00):
        hits = find_all(q(tgt), blocks=(".rdata", ".data"))
        print("  qword %#x found at %s" % (tgt, [hex(h) for h in hits]))

    print("\n##### A: DiscardCard vtable 0x180220488 #####")
    slots = vtable(0x180220488, 32)
    fns = []
    for off, tgt, nm in slots:
        print("   +%#05x %#x %s" % (off, tgt, nm))
        if nm:
            fns.append(tgt)
    print("\n##### A2: decompile every DiscardCard slot #####")
    seen = set()
    for t in fns:
        if t in seen:
            continue
        seen.add(t)
        dump("DiscardCard slot", t, "qs_dcslot_%x.txt" % t)

    print("\n##### A3: DiscardCardByRes + bulk vtables #####")
    for tgt in (0x1801279c0, 0x180126f40):
        for h in find_all(q(tgt), blocks=(".rdata", ".data")):
            base = h - 8
            print("  --- vtable base guess %#x (slot+0x08 == %#x) ---" % (base, tgt))
            for off, t2, nm in vtable(base, 24):
                print("     +%#05x %#x %s" % (off, t2, nm))

    print("\n##### B: the FUT manager singleton #####")
    dump("FUN_18011d780 (writes DAT_1802e6398)", 0x18011d780, "qs_mgr_set.txt")
    dump("FUN_180119110", 0x180119110, "qs_mgr_119110.txt")
    dump("FUN_18011e3c0", 0x18011e3c0, "qs_mgr_11e3c0.txt")
    dump("FUN_18011e9d0", 0x18011e9d0, "qs_mgr_11e9d0.txt")

    print("\n##### C: item registration + item+0x38/0x3c readers #####")
    # find the manager vtable from the ctor and dump the 0x9c0..0xa90 window
    print("  (vtable window printed below once the ctor reveals the table address)")

    print("\n##### E: RS4 discard literals and their neighbourhoods #####")
    for nm in ("FutDiscardCardServerResponse", "FutDiscardCardByResServerResponse"):
        for h in find_all(b"RS4:" + nm.encode() + b"\x00"):
            print("  %s @ %#x" % (nm, h))
            for frm, typ, fn2, ent in xrefs_to(h - 4):
                print("     xref %#x %s %s %#x" % (frm, typ, fn2, ent))
                if ent:
                    dump("factory", ent, "qs_factory_%x.txt" % ent)
    print("  all RS4: literals containing 'Discard':")
    for h in find_all(b"RS4:Fut"):
        s = rd_str(h, 80)
        if "iscard" in s or "Item" in s:
            print("     %#x %r" % (h, s))

except Exception:
    traceback.print_exc()
