"""D2 QUICK SELL ECONOMY, batch 1.

HYPOTHESIS (from an earlier agent's decompile of the shared ITEM element deser
FUN_18013fe00, scratchpad/packres/d4_item_deser.txt lines 779-801): the client
computes a card's quick-sell value LOCALLY, from a game-database table called
"fcc_discardcoins", ONLY when the server-sent discardValue (atom 0xd7) is zero:

    if ((int)local_150 == 0) {                       // discardValue not sent / 0
      q = select "price" from "fcc_discardcoins"
            where cardtype = local_13c               // = f(cardsubtypeid)
              and level    = local_138._4_4_
              and <DAT_18022315c> = uStack_130 & 0xffffffff   // = rareflag
      p = q.row0["price"]
      v = (rating * p) / 100, round half up at remainder > 0x31
      local_150.hi = v
    }

QUESTIONS THIS BATCH ANSWERS
  A. what is the string at DAT_18022315c (the third query key)?
  B. where does "level" (local_138._4_4_) come from? no JSON atom in the switch
     writes it, so read the RAW INSTRUCTIONS, not the decompiler's locals.
  C. what is FUN_1800d8330 (cardsubtypeid -> cardtype)?
  D. what are the db-query wrapper functions 0x1801a0020 / 0x18019fd10 /
     0x18019fd40 / 0x1801a0280 / 0x1801a0000 / 0x18019ff00 / 0x18019ffc0 /
     0x18019fea0 / 0x1801a00a0 / 0x1801a0080 / 0x18019fe40 / 0x18019fe10,
     i.e. confirm this really is a SELECT col FROM table WHERE k=v chain, and
     find the underlying dbdata entry point so the table can be located live.
  E. Q2: FutDiscardCardServerResponse deser 0x180127300 stores totalCredits at
     resp+0x28. WHO reads resp+0x28, and does it ASSIGN or ACCUMULATE?
  F. Q3: bulk discard. FUN_180126f40 builds a body {"itemId":[...]} (atom 0x16d).
     which action/route uses it? print its callers and their callers.

CONTROLS
  * class_deser is known-broken in rebuilt projects, so classes are resolved with
    find_all(b"RS4:" + name). CONTROL: RS4:FutSquadSaveServerResponse must be
    found exactly once at 0x18022c618 (measured on disk this session). If that
    fails the whole batch is suspect.
  * CONTROL for the atom-arm search: the ITEM deser must contain an arm for atom
    0x274 (rating) AND one for 0xd7 (discardValue); both are switch-case labels,
    the same syntactic form as anything else searched for here.

Everything is printed in full with len() stated. Nothing is truncated.
"""
import traceback, os

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, NOT TRUNCATED)"
          % (tag, va, fname(va), len(src)))
    print("=" * 78)
    print(src)
    if path:
        open(OUT + path, "w").write("// %s %#x len=%d\n%s" % (tag, va, len(src), src))
    return src


def disasm(lo, hi, tag):
    print("-" * 78)
    print("ASM %s  %#x..%#x" % (tag, lo, hi))
    print("-" * 78)
    a = addr(lo)
    while int(a.getOffset()) < hi:
        ins = listing.getInstructionAt(a)
        if ins is None:
            a = a.add(1)
            continue
        print("%#x  %s" % (int(a.getOffset()), str(ins)))
        a = ins.getAddress().add(ins.getLength())


try:
    print("##### CONTROL 0: RS4 literal lookup #####")
    for nm in ("FutSquadSaveServerResponse", "FutDiscardCardServerResponse",
               "FutDiscardCardByResServerResponse", "FutDiscardACardServerResponse"):
        h = find_all(b"RS4:" + nm.encode() + b"\x00")
        print("  RS4:%-40s hits=%s" % (nm, [hex(x) for x in h]))

    print("\n##### A: strings used by the discardcoins query #####")
    for nm, a in (("DAT_18022315c", 0x18022315c), ("fcc_discardcoins_lit", 0x1802231f0),
                  ("DAT_1801eeeb0", 0x1801eeeb0), ("DAT_1802ef590", 0x1802ef590)):
        try:
            print("  %-22s %#x -> %r  bytes=%s"
                  % (nm, a, rd_str(a, 64), read_bytes(a, 24).hex()))
        except Exception as e:
            print("  %-22s %#x -> ERR %r" % (nm, a, e))
    # neighbourhood of the literal pool so column names are visible
    try:
        blob = read_bytes(0x180223100, 0x200)
        print("  literal pool 0x180223100..0x180223300:")
        for piece in blob.split(b"\x00"):
            if len(piece) >= 3:
                print("     %r" % piece)
    except Exception as e:
        print("  pool ERR %r" % e)
    try:
        print("  _DAT_1801f66a0 16 bytes = %s" % read_bytes(0x1801f66a0, 16).hex())
    except Exception as e:
        print("  _DAT_1801f66a0 ERR %r" % e)

    print("\n##### B: raw instructions of the discardcoins block in the ITEM deser #####")
    # the query build sits after atom dispatch; xref to the literal pins it
    for frm, typ, fn, ent in xrefs_to(0x1802231f0):
        print("  xref to fcc_discardcoins literal: from %#x %s in %s (%#x)"
              % (frm, typ, fn, ent))
    disasm(0x180140f80, 0x1801411e0, "item deser: discardcoins query build")

    print("\n##### B2: every write to the two stack slots feeding cardtype/level #####")
    print("  (searching the whole ITEM deser for MOV [RBP+..] style stores is noisy;")
    print("   instead: full decompile is dumped to disk, and the asm above is authoritative)")
    dump("ITEM element deser FUN_18013fe00", 0x18013fe00, "qs_item_deser.txt")

    print("\n##### C: cardsubtypeid -> cardtype #####")
    dump("FUN_1800d8330 cardsubtype->cardtype", 0x1800d8330, "qs_d8330.txt")
    dump("FUN_1800d84e0", 0x1800d84e0, "qs_d84e0.txt")

    print("\n##### D: the db query wrapper chain #####")
    for a in (0x1801a0020, 0x18019fd10, 0x18019fd40, 0x1801a0280, 0x1801a0000,
              0x18019ff00, 0x18019ffc0, 0x18019fea0, 0x1801a00a0, 0x1801a0080,
              0x18019fe40, 0x18019fe10):
        dump("dbquery %#x" % a, a, "qs_db_%x.txt" % a)

    print("\n##### E: discard response consumers #####")
    dump("FutDiscardCard deser FUN_180127300", 0x180127300, "qs_discard_deser.txt")
    dump("FUN_1800d7af0 (int conv used on totalCredits)", 0x1800d7af0, "qs_d7af0.txt")
    print("  --- callers of the discard deser / its owning class ---")
    for frm, typ, fn, ent in xrefs_to(0x180127300):
        print("   xref %#x %s %s %#x" % (frm, typ, fn, ent))
    # the singleton FUN_18011a830 vtable: slot 0xa30 removes an item; find the
    # credits setter near it
    dump("singleton getter FUN_18011a830", 0x18011a830, "qs_singleton.txt")

    print("\n##### F: bulk discard #####")
    dump("bulk discard body builder FUN_180126f40", 0x180126f40, "qs_bulkbody.txt")
    dump("single discard url builder FUN_180127570", 0x180127570, "qs_urlbuild.txt")
    for a in (0x180126f40, 0x180127570):
        print("  --- xrefs to %#x ---" % a)
        for frm, typ, fn, ent in xrefs_to(a):
            print("    %#x %s %s %#x" % (frm, typ, fn, ent))
            if ent:
                for f2, t2, n2, e2 in xrefs_to(ent):
                    print("        ^ %#x %s %s %#x" % (f2, t2, n2, e2))

    print("\n##### F2: action table rows for the three discard actions #####")
    for nm, rowa in (("DiscardCard", 0x1802cb230), ("DiscardCardByRes", 0x1802cb260),
                     ("DiscardACard", 0x1802cb290)):
        try:
            print("  %s row %#x bytes=%s" % (nm, rowa, read_bytes(rowa, 0x30).hex()))
        except Exception as e:
            print("  %s ERR %r" % (nm, e))
        for frm, typ, fn, ent in xrefs_to(rowa):
            print("     xref %#x %s %s %#x" % (frm, typ, fn, ent))

except Exception:
    traceback.print_exc()
