"""D4 Q3/Q4 part 2. The pack-open summary builder FUN_1800aa440 picks a headline item
and builds a display struct. Decompile everything it leans on:

  0x18013fe00  shared ITEM element deserializer  -> atom -> struct offset map, so we can
               name the fields FUN_1800aa440 reads (+0x18, +0x38, +0x3c, +0x4c, +0x58,
               +0x94, +0xb4, +0x146, +0x148)
  0x1800aa330  the headline predicate  (does this item qualify for the special path)
  0x1800a9fe0  called with (item[0xb], item.byte@0xb4) -> stored as a display field.
               Prime suspect for the animation-style / tier number.
  0x1800aa060  per-top-3-item expander
  0x1800a96a0  the sort over the collected (a,b,c,index) tuples  <- Q4 lives here
  0x1800a9b10  display-struct init
  0x1800a9a10  display-struct -> event payload
  callers of 0x1800aa440

CONTROL: the item deserializer must reproduce a field we already know from
docs/CARD_SYSTEM.md / ENDPOINT_MAP.md, e.g. atom 0x271 rareflag and atom 0x6c
cardsubtypeid must both appear in its atom ladder. If they do not, I have the wrong
function and the offset map is worthless.
"""
import traceback

OUT = "/tmp/claude-1000/-home-alex-Documents-OpenFUT/8e521ca1-ca3e-4138-bb96-df1744dd1d30/scratchpad/packres/"
BUF = []


def p(*a):
    s = " ".join(str(x) for x in a)
    print(s)
    BUF.append(s)


try:
    for va, nm in ((0x18013FE00, "item_deser"),
                   (0x1800AA330, "headline_predicate"),
                   (0x1800A9FE0, "style_from_item"),
                   (0x1800AA060, "top3_expander"),
                   (0x1800A96A0, "sort"),
                   (0x1800A9B10, "disp_init"),
                   (0x1800A9A10, "disp_to_event")):
        src = dec(va, 300)
        p("\n\n########## %s %#x len=%d ##########" % (nm, va, len(src)))
        p(src)
        with open(OUT + "d4_%s.txt" % nm, "w") as f:
            f.write(src)

    p("\n=== callers of FUN_1800aa440 (pack-open summary) ===")
    for c in callers(0x1800AA440):
        p("   %s" % (c,))
    p("=== callers of FUN_1800a9fe0 ===")
    for c in callers(0x1800A9FE0):
        p("   %s" % (c,))
    p("=== callers of FUN_1800aa330 ===")
    for c in callers(0x1800AA330):
        p("   %s" % (c,))

except Exception:
    traceback.print_exc()
finally:
    with open(OUT + "d4_reveal_path2.txt", "w") as f:
        f.write("\n".join(BUF))
    print("WROTE d4_reveal_path2.txt")
