"""Read the sublevel records and initial monsters of a decoded LEVELn.INF.

Shared by scripts/maps/make_level_maps.py and scripts/monsters/make_bestiary.py.
The layout follows formats/INF.ksy; the input is the payload of the CPS
container, decoded with tools/uncps.py.
"""
import struct


def dice(d, p):
    """A dice triplet (formats/INF.ksy, type dice): rolls, sides and a signed bonus."""
    return d[p], d[p + 1], struct.unpack_from("<b", d, p + 2)[0]


def monster_type(d, p):
    """The properties of one monster type (formats/INF.ksy, type monster_properties)."""
    s1 = lambda at: struct.unpack_from("<b", d, at)[0]
    u16 = lambda at: struct.unpack_from("<H", d, at)[0]
    e = {"armor_class": s1(p), "hit_chance": s1(p + 1), "level": s1(p + 2),
         "hit_points_dice": dice(d, p + 3), "attacks_per_round": d[p + 6],
         "damage_dice": [dice(d, p + 7 + 3 * i) for i in range(3)],
         "immunity_flags": u16(p + 16), "capability_flags": u16(p + 18),
         "type_flags": u16(p + 20), "experience": u16(p + 22),
         "occupancy_class": d[p + 24], "sound_1": s1(p + 25), "sound_2": s1(p + 26),
         "remote_attack_count": d[p + 27]}
    q = p + 28
    marker = d[q]; q += 1
    e["remote_weapon_change_mode"], e["remote_weapons"] = None, []
    if marker != 0xff:
        e["remote_weapon_change_mode"] = d[q]
        count = s1(q + 1)
        q += 2
        e["remote_weapons"] = [struct.unpack_from("<h", d, q + 2 * i)[0] for i in range(max(count, 0))]
        q += 2 * max(count, 0)
    e["turn_resistance"] = s1(q)
    e["damage_modifier"] = d[q + 1]
    e["decoration_indices"] = list(d[q + 2:q + 5])
    return e


def name13(raw):
    return raw.split(b"\0", 1)[0].decode("ascii", "replace")


# --------------------------------------------------------------------------- files

def parse_sublevel(d, start):
    """One sublevel record (formats/INF.ksy, type sublevel)."""
    u16 = lambda at: struct.unpack_from("<H", d, at)[0]
    p = start
    rec = {"next": u16(p)}
    p += 2
    marker = d[p]; p += 1
    if marker == 0xec:
        rec["maze"] = name13(d[p:p + 13]); p += 13
        rec["graphics"] = name13(d[p:p + 13]); p += 13
        pm = d[p]; p += 1
        if pm != 0xff:
            p += 13
    rec["sound"] = name13(d[p:p + 13]); p += 13
    rec["doors"] = []
    for _ in range(2):
        m = d[p]; p += 1
        if m in (0xec, 0xea):
            rec["doors"].append({"image": name13(d[p:p + 13]), "graphic": d[p + 13],
                                 "kind": d[p + 14], "no_switch": d[p + 15]})
            p += 13 + 3 + 3 * 8 + 2 * 12
    rec["steps"] = u16(p); p += 2
    rec["banks"] = {}
    for _ in range(2):
        m = d[p]; p += 1
        if m == 0xec:
            dst = d[p + 1]
            rec["banks"][dst] = name13(d[p + 2:p + 15])
            p += 2 + 13 + 1
    rec["types"] = []
    rec["type_entries"] = {}
    while True:
        t = d[p]; p += 1
        if t == 0xff:
            break
        rec["types"].append(t)
        rec["type_entries"][t] = monster_type(d, p)
        p += 28
        remote_marker = d[p]; p += 1
        if remote_marker != 0xff:
            count = struct.unpack_from("<b", d, p + 1)[0]
            p += 2 + 2 * max(count, 0)
        p += 5
    rec["mappings"] = {}
    if d[p] == 0xec:
        p += 1
        n = u16(p); p += 2
        for _ in range(n):
            m = d[p]; p += 1
            if m == 0xec:
                p += 26
            else:
                wall, vmp, dec, special, flags = struct.unpack_from("<BBbBB", d, p)
                p += 5
                rec["mappings"][wall] = {"vmp": vmp, "decoration": dec,
                                         "special": special, "flags": flags}
    else:
        p += 1
    rec["timers"] = []
    while u16(p) != 0xffff:
        rec["timers"].append((u16(p), u16(p + 2)))
        p += 4
    rec["end"] = p + 2
    return rec


def sublevels(d):
    state = struct.unpack_from("<H", d, 0)[0]
    records, start = [], 2
    while True:
        rec = parse_sublevel(d, start)
        records.append(rec)
        nxt = 2 + rec["next"]
        if not (start < nxt < state):
            return records
        start = nxt


def initial_monsters(d):
    state = struct.unpack_from("<H", d, 0)[0]
    if d[state + 2] != 0xec:
        return []
    p = state + 3
    while d[p] != 0xff:
        p += 2
    p += 1
    out = []
    for i in range(30):
        slot, unit, block, pos, direction, typ, gfx, mode, param = struct.unpack_from(
            "<BBHBbBBBB", d, p + 14 * i)
        # A record of block 0 places nothing: the game leaves the slot empty.
        if slot != 0xff and block != 0:
            out.append({"block": block, "position": pos, "direction": direction,
                        "type": typ, "bank": 0 if gfx == 0 else 1, "mode": mode})
    return out
