#!/usr/bin/env python3
"""Reachability-based decoder for the EOB II level script language (research tool).

Target: DOS EOB II `LEVELn.INF` payloads (LCW-decoded with tools/uncps.py). The instruction
layouts follow docs/scripting/ (DOS START.EXE, analysis addresses 0x25a15-0x27a9a). The tool
never scans for opcode-looking bytes: it starts from the script references of the INF cell
bindings and follows control flow, as the original dispatcher at 0x27b37 does.

Dispatcher rule used here (START.EXE, analysis addresses 0x27b37-0x27b6a): a signed byte that is
neither negative nor above -0x1f (that is, any byte 0x00-0xe1) is skipped as a one-byte no-op;
bytes 0xe2-0xff select an instruction.

Instruction encodings whose layout is not documented (unknown selectors) end the path and are
reported; nothing is guessed. This is an analysis aid, not a regression test. It reads the
originals and writes only to stdout.

Usage (from the repository root; --game DIR reads the game files from another directory):
    python3 -I scripts/inf/script_decoder.py                    # summary of all 16 levels
    python3 -I scripts/inf/script_decoder.py --listing 7        # decoded listing of level 7
    python3 -I scripts/inf/script_decoder.py --gaps 7           # unreached ranges of level 7
    python3 -I scripts/inf/script_decoder.py --usage            # selector values seen per opcode
"""
import argparse
import importlib.util
import struct
import sys
from collections import Counter, defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
ORIGINALS = ROOT / "data" / "originals" / "eob2"   # replaced by --game
# uncps.py is looked for next to this file first, then in the repository's tools/.
UNCPS = HERE / "uncps.py" if (HERE / "uncps.py").exists() else ROOT / "tools" / "uncps.py"
LEVEL_COUNT = 16

NAMES = {
    0xff: "SET", 0xfe: "TOGGLE", 0xfd: "OPEN_DOOR", 0xfc: "CLOSE_DOOR",
    0xfb: "SPAWN_MONSTER", 0xfa: "MOVE_PARTY_OR_OBJECT",
    0xf9: "MOVE_INVENTORY_ITEM_TO_BLOCK", 0xf8: "PRINT_MESSAGE", 0xf7: "SET_FLAGS",
    0xf6: "PLAY_SOUND", 0xf5: "CLEAR_FLAGS", 0xf4: "MODIFY_CHARACTER_HP",
    0xf3: "DAMAGE_CHARACTERS", 0xf2: "JUMP", 0xf1: "END", 0xf0: "RETURN", 0xef: "CALL",
    0xee: "JUMP_UNLESS", 0xed: "DELETE_ITEM", 0xec: "LOAD_LEVEL_OR_MONSTERS",
    0xeb: "AWARD_EXPERIENCE", 0xea: "CREATE_ITEM", 0xe9: "LAUNCH_OBJECT",
    0xe8: "CHANGE_DIRECTION", 0xe7: "IDENTIFY_ITEMS", 0xe6: "RUN_SEQUENCE", 0xe5: "DELAY",
    0xe4: "DRAW_SCENE", 0xe3: "DIALOGUE", 0xe2: "SPECIAL_EVENT",
}
OPERATORS = {0xff: "==", 0xfe: "!=", 0xfd: "<", 0xfc: "<=", 0xfb: ">", 0xfa: ">=",
             0xf9: "AND", 0xf8: "OR"}


def P(block):
    """A block index as a level position [XX:YY] (column, row)."""
    return f"[{block % 32:02d}:{block // 32:02d}]"


class Truncated(Exception):
    """An operand would be read beyond the script buffer."""


class UnknownLayout(Exception):
    """The opcode or selector has no documented operand layout."""


class Reader:
    def __init__(self, buf, pos):
        self.buf, self.pos = buf, pos

    def _take(self, n):
        if self.pos + n > len(self.buf):
            raise Truncated()
        value = self.buf[self.pos:self.pos + n]
        self.pos += n
        return value

    def u8(self):
        return self._take(1)[0]

    def s8(self):
        return struct.unpack("<b", self._take(1))[0]

    def u16(self):
        return struct.unpack("<H", self._take(2))[0]

    def s16(self):
        return struct.unpack("<h", self._take(2))[0]

    def raw(self, n):
        return bytes(self._take(n))


class Insn:
    """One decoded instruction. flow is one of seq, jump, call, cond, end, return, stop."""

    def __init__(self, pos, opcode):
        self.pos, self.opcode = pos, opcode
        self.length = 1
        self.text = ""
        self.flow = "seq"
        self.target = None
        self.message_refs = []   # string indices that the instruction resolves
        self.key = NAMES.get(opcode, "SKIP")


TOKEN_NAMES = {
    0xff: "EQUAL", 0xfe: "NOT_EQUAL", 0xfd: "LESS", 0xfc: "LESS_OR_EQUAL", 0xfb: "GREATER",
    0xfa: "GREATER_OR_EQUAL", 0xf9: "AND", 0xf8: "OR", 0xd2: "CONSTANT", 0xef: "LEVEL_FLAG",
    0xf0: "GLOBAL_FLAG", 0xf1: "PARTY_BLOCK_OR_ITEM_HOLDERS", 0xf7: "BLOCK_FIRST_BYTE",
    0xe9: "BLOCK_BYTE", 0xf3: "BLOCK_OCCUPANCY_OR_MONSTER_COUNT", 0xf2: "ITEM_IN_BLOCK",
    0xf5: "BLOCK_ITEM_TYPE_COUNT", 0xe7: "HELD_ITEM", 0xd7: "LAST_USED_ITEM", 0xdb: "ROLL_DICE",
    0xe8: "ACTIVE_CHARACTER_COUNT", 0xda: "NO_ELIGIBLE_CHARACTER", 0xed: "PARTY_DIRECTION",
    0xce: "FIND_CHARACTER_BY_PORTRAIT", 0xdd: "FIND_CHARACTER_BY_RACE",
    0xdc: "FIND_CHARACTER_BY_CLASS_MASK", 0xe0: "EVENT_MASK", 0xe4: "RUN_VARIABLE", 0xdf: "LAST_CAST_SPELL",
}


def expression(r):
    """Decode a 0xee expression. Returns (tokens, final stack depth, token kinds). Mirrors 0x267a7."""
    depth, out, kinds = 0, [], []
    while True:
        t = r.u8()
        if t == 0xee:
            break
        if t < 0xce:
            continue                       # skipped one-byte no-op
        if t in TOKEN_NAMES:
            kinds.append(t)
        if t in OPERATORS:
            depth -= 1
            out.append(OPERATORS[t])
        elif t == 0xd2:
            out.append(str(r.u16())); depth += 1
        elif t in (0xef, 0xf0):
            out.append(("LEVEL_FLAG" if t == 0xef else "GLOBAL_FLAG") + f"[{r.u8()}]"); depth += 1
        elif t == 0xf7:
            out.append(f"BLOCK_BYTE0[{P(r.u16())}]"); depth += 1
        elif t == 0xe9:
            off = r.s8(); out.append(f"BLOCK_BYTE[{P(r.u16())}+{off}]"); depth += 1
        elif t == 0xf3:
            sel = r.u8()
            if sel == 0xff:
                out.append(f"BLOCK_OCCUPANCY[{P(r.u16())}]")
            else:
                types = []
                while True:
                    b = r.u8()
                    if b == 0xff:
                        break
                    types.append(b)
                out.append(f"MONSTER_COUNT{types}")
            depth += 1
        elif t == 0xf2:
            item, block = r.u16(), r.u16(); out.append(f"ITEM_IN_BLOCK[{item},{P(block)}]"); depth += 1
        elif t == 0xf5:
            flag, typ, block = r.u8(), r.s8(), r.u16()
            out.append(f"BLOCK_ITEM_TYPE_COUNT[type={typ},flag={flag},{P(block)}]"); depth += 1
        elif t == 0xf1:
            sel = r.u8()
            if sel == 0xf5:
                a, b = r.u16(), r.u16(); out.append(f"PARTY_ITEM_HOLDERS[{a},{b}]")
            else:
                out.append(f"PARTY_BLOCK=={P(r.u16())}")
            depth += 1
        elif t in (0xe7, 0xd7):
            sel = r.u8()
            name = "HELD_ITEM" if t == 0xe7 else "LAST_USED_ITEM"
            allowed = {0xf5: "INDEX", 0xe1: "TYPE", 0xf6: "VALUE"}
            if t == 0xe7:
                allowed.update({0xd0: "UNIDENTIFIED_NAME_CONTAINS", 0xcf: "IDENTIFIED_NAME_CONTAINS"})
            else:
                allowed[0xdc] = "TYPE_PROPERTIES"
            if sel in (0xd0, 0xcf) and t == 0xe7:
                n = r.u8(); r.raw(n); out.append(f"{name}.{allowed[sel]}(<{n} bytes>)"); depth += 1
            elif sel in allowed:
                out.append(f"{name}.{allowed[sel]}"); depth += 1
            else:
                out.append(f"{name}.?{sel:#04x}")   # pushes nothing in the original
        elif t == 0xdb:
            c, s, b = r.s8(), r.s8(), r.s8(); out.append(f"DICE[{c}d{s}{b:+d}]"); depth += 1
        elif t == 0xce:
            out.append(f"FIND_CHAR_BYTE24[{r.s8()}]"); depth += 1
        elif t == 0xdd:
            out.append(f"FIND_CHAR_BYTE21[{r.u8()}]"); depth += 1
        elif t == 0xdc:
            out.append(f"FIND_CHAR_CLASS_MASK[{r.u8():#04x}]"); depth += 1
        elif t in (0xe8, 0xda, 0xed, 0xe0, 0xe4, 0xdf):
            out.append({0xe8: "ACTIVE_CHARACTER_COUNT", 0xda: "NO_ELIGIBLE_CHARACTER",
                        0xed: "PARTY_DIRECTION", 0xe0: "EVENT_MASK", 0xe4: "RUN_VARIABLE",
                        0xdf: "LAST_CAST_SPELL"}[t]); depth += 1
        # every other value in 0xce-0xff is a documented no-op
    return out, depth, kinds


def move_items(r, filtered):
    parts = []
    if filtered:
        parts.append(f"item_type={r.s16()}")
    for end in ("source", "destination"):
        marker = r.u8()
        level = r.s8() if marker != 0xeb else None
        block = r.u16()
        parts.append(f"{end}=" + ("current" if level is None else f"marker {marker:#04x} level {level}")
                     + f" {P(block)}")
    return ", ".join(parts)


def decode(buf, pos):
    """Decode the command at pos (buf[pos] >= 0xe2). Raises Truncated or UnknownLayout."""
    op = buf[pos]
    insn = Insn(pos, op)
    r = Reader(buf, pos + 1)
    if op == 0xff:                                            # SET
        sel = r.u8()
        if sel == 0xf7:
            insn.text = f"BLOCK_WALLS {P(r.u16())} wall {r.u8()}"
        elif sel == 0xe9:
            b = r.u16(); s = r.s8(); insn.text = f"BLOCK_SIDE {P(b)} side {s} wall {r.u8()}"
        elif sel == 0xed:
            insn.text = f"DIRECTION {r.s8()}"
        else:
            raise UnknownLayout(f"selector {sel:#04x}")
    elif op == 0xfe:                                          # TOGGLE
        sel = r.u8()
        if sel == 0xf7:
            b = r.u16(); f = r.u8(); insn.text = f"BLOCK_WALLS {P(b)} first {f} second {r.u8()}"
        elif sel == 0xe9:
            b = r.u16(); s = r.s8(); f = r.u8()
            insn.text = f"BLOCK_SIDE {P(b)} side {s} first {f} second {r.u8()}"
        elif sel == 0xea:
            insn.text = f"DOOR {P(r.u16())}"
        else:
            raise UnknownLayout(f"selector {sel:#04x}")
    elif op in (0xfd, 0xfc):                                  # OPEN_DOOR, CLOSE_DOOR
        insn.text = P(r.u16())
    elif op == 0xfb:                                          # SPAWN_MONSTER
        skipped = r.u8(); unit = r.s8(); block = r.u16()
        position, direction, type_index, graphics, mode, parameter = (r.s8() for _ in range(6))
        random_item, fixed_item = r.u16(), r.u16()
        insn.text = (f"skipped={skipped:#04x} unit={unit} block={P(block)} position={position} "
                     f"direction={direction} type={type_index} graphics={graphics} mode={mode} "
                     f"parameter={parameter} random_item={random_item} fixed_item={fixed_item}")
    elif op == 0xfa:                                          # MOVE_PARTY_OR_OBJECT
        sel = r.u8()
        if sel in (0xe1, 0xf5):
            insn.text = ("ITEMS_FILTERED " if sel == 0xe1 else "ITEMS ") + move_items(r, sel == 0xe1)
        else:
            a, b = r.u16(), r.u16()
            if sel == 0xe8:
                insn.text = f"PARTY ignored={a} -> {P(b)}"
            elif sel == 0xf3:
                insn.text = f"MONSTERS {P(a)} -> {P(b)}"
            else:
                insn.text = f"OTHER_{sel:#04x} {a} {b}"
    elif op == 0xf9:                                          # MOVE_INVENTORY_ITEM_TO_BLOCK
        c = r.s8(); b = r.u16(); insn.text = f"character {c} {P(b)} position {r.s8()}"
    elif op == 0xf8:                                          # PRINT_MESSAGE
        idx = r.u16(); color = r.s8(); r.u8()
        insn.text = f"string {idx} color {color}"; insn.message_refs.append(idx)
    elif op == 0xf7 or op == 0xf5:                            # SET_FLAGS, CLEAR_FLAGS
        sel = r.u8()
        if sel in (0xef, 0xf0):
            insn.text = ("LEVEL" if sel == 0xef else "GLOBAL") + f" bit {r.u8()}"
        elif sel == 0xf3 and op == 0xf7:
            slot = r.s8(); insn.text = f"MONSTER slot {slot} bit {r.s8()}"
        elif sel in (0xe4, 0xd1):
            insn.text = "RUN_VARIABLE" if sel == 0xe4 else "REST_ALLOWED"
        else:
            raise UnknownLayout(f"selector {sel:#04x}")
    elif op == 0xf6:                                          # PLAY_SOUND
        s = r.s8(); insn.text = f"sound {s} at {P(r.u16())}"
    elif op == 0xf4:                                          # MODIFY_CHARACTER_HP
        c = r.s8(); insn.text = f"character {c} adjustment {r.s8()}"
    elif op == 0xf3:                                          # DAMAGE_CHARACTERS
        c = r.s8(); times, sides, bonus, flags, save_type, save_effect = (r.s8() for _ in range(6))
        insn.text = (f"character={'ALL' if c == -1 else c} dice={times}d{sides}{bonus:+d} "
                     f"flags={flags & 0xff:#04x} save_type={save_type} save_effect={save_effect}")
    elif op in (0xf2, 0xef):                                  # JUMP, CALL
        insn.target = r.u16()
        insn.flow = "jump" if op == 0xf2 else "call"
        insn.text = f"-> {insn.target}"
    elif op in (0xf1, 0xf0):                                  # END, RETURN
        insn.flow = "end" if op == 0xf1 else "return"
    elif op == 0xee:                                          # JUMP_UNLESS
        tokens, depth, kinds = expression(r)
        insn.tokens = kinds
        insn.target = r.u16()
        insn.flow = "cond"
        insn.text = " ".join(tokens) + f" ; else -> {insn.target}"
        insn.depth = depth
    elif op == 0xed:                                          # DELETE_ITEM
        sel = r.u8()
        insn.text = "HELD_ITEM" if sel == 0xff else (
            ("ALL_IN_BLOCK" if sel == 0xfe else f"TYPE {struct.unpack('<b', bytes([sel]))[0]}")
            + f" {P(r.u16())}")
    elif op == 0xec:                                          # LOAD_LEVEL_OR_MONSTERS
        sel = r.u8()
        if sel == 0xe5:
            lv, sub, block = r.s8(), r.s8(), r.u16()
            insn.text = f"LEVEL {lv} sublevel {sub} {P(block)} direction {r.s8()}"
            insn.flow = "stop"
        else:
            idx, grp = r.s8(), r.s8(); name = r.raw(13)
            insn.text = f"MONSTERS selector {sel:#04x} loader {idx} slot_group {grp} name <13 bytes>"
    elif op == 0xeb:                                          # AWARD_EXPERIENCE
        sel = r.u8()
        insn.text = f"PARTY {r.s16()}" if sel == 0xe2 else f"selector {sel:#04x}"
    elif op == 0xea:                                          # CREATE_ITEM
        tmpl, dest, pos_, mask = r.u16(), r.u16(), r.s8(), r.u8()
        extras = []
        for bit, label in ((1, "value"), (2, "flags"), (4, "icon")):
            if mask & bit:
                extras.append(f"{label}={r.u8()}")
        where = f"{dest:#06x}" if dest >= 0xfffe else P(dest)
        insn.text = f"template {tmpl} destination {where} position {pos_} mask {mask:#04x} {' '.join(extras)}"
    elif op == 0xe9:                                          # LAUNCH_OBJECT
        kind, obj, block, d, off = r.u8(), r.u16(), r.u16(), r.s8(), r.s8()
        insn.text = f"kind {kind:#04x} object {obj:#06x} {P(block)} direction {d} offset {off}"
    elif op == 0xe8:                                          # CHANGE_DIRECTION
        t = r.u8(); insn.text = f"target {t:#04x} adjustment {r.s8()}"
    elif op == 0xe7:                                          # IDENTIFY_ITEMS
        insn.text = P(r.u16())
    elif op == 0xe6:                                          # RUN_SEQUENCE
        insn.text = f"selector {r.s8()}"
    elif op == 0xe5:                                          # DELAY
        insn.text = f"duration {r.s16()}"
    elif op == 0xe4:                                          # DRAW_SCENE
        pass
    elif op == 0xe3:                                          # DIALOGUE
        sel = r.u8()
        if sel == 0xd3:
            r.raw(13); frame = r.s8(); x, y, flags = r.u16(), r.u16(), r.u16()
            insn.text = f"BITMAP name <13 bytes> frame {frame} source ({x},{y}) flags {flags:#06x}"
        elif sel in (0xd4, 0xd5, 0xd6):
            insn.text = {0xd4: "RESTORE", 0xd5: "INITIALIZE", 0xd6: "BOX"}[sel]
        elif sel == 0xd8:
            w = [r.u16() for _ in range(4)]
            insn.text = f"CHOICE text_id {w[0]} options {w[1:]}"; insn.message_refs += w[1:]
        elif sel == 0xf8:
            tid, idx = r.u16(), r.u16(); insn.text = f"TEXT text_id {tid} prompt {idx}"
            insn.message_refs.append(idx)
        else:
            insn.text = f"selector {sel:#04x}"            # handler returns after the selector
    elif op == 0xe2:                                          # SPECIAL_EVENT
        insn.text = f"event {r.u16()}"
    else:
        raise UnknownLayout("opcode")
    insn.length = r.pos - pos
    return insn



def selector_of(insn, buf):
    """The selector-like operand of an instruction, as a printable value, or None."""
    op, at = insn.opcode, insn.pos
    if op in (0xff, 0xfe, 0xfa, 0xf7, 0xf5, 0xed, 0xec, 0xeb, 0xe3, 0xe8):
        return f"{buf[at + 1]:#04x}"
    if op == 0xe9:                                    # kind byte
        return f"{buf[at + 1]:#04x}"
    if op == 0xe6:                                    # signed selector
        return f"{struct.unpack('<b', buf[at + 1:at + 2])[0]}"
    if op == 0xe2:                                    # u16 event
        return f"{struct.unpack_from('<H', buf, at + 1)[0]}"
    if op == 0xea:                                    # override mask, destination
        dest = struct.unpack_from("<H", buf, at + 3)[0]
        return f"mask {buf[at + 6]:#04x} destination " + (f"{dest:#06x}" if dest >= 0xfffe else "block")
    return None


def classify_gap(level, insns, owner, start, end):
    """Label an unreached range: dead code after a non-returning command, or unreferenced."""
    prev = owner.get(start - 1)
    if prev is not None:
        p = insns[prev]
        if prev + p.length == start and p.flow in ("stop", "end", "return", "jump"):
            return f"after-{p.key}"
    return "unreferenced"


class Level:
    def __init__(self, number, data):
        self.number, self.data = number, data
        state = struct.unpack_from("<H", data, 0)[0]
        self.bindings_offset = struct.unpack_from("<H", data, state)[0]
        marker = data[state + 2]
        p = state + 3
        if marker == 0xec:                    # monster timers then 30 monster slots (INF.ksy)
            while data[p] != 0xff:
                p += 2
            p += 1 + 30 * 14
        self.script_start = p
        self.buf = data[p:self.bindings_offset]
        self.message_offset = struct.unpack_from("<H", self.buf, 0)[0]
        count = struct.unpack_from("<H", data, self.bindings_offset)[0]
        self.bindings = [struct.unpack_from("<HHH", data, self.bindings_offset + 2 + 6 * i)
                         for i in range(count)]
        self.message_count = self.buf[self.message_offset:].count(b"\0")


def game_file(name):
    """A file of the game directory, whatever the case of its name on disk."""
    path = Path(ORIGINALS) / name
    if not path.exists():
        for candidate in Path(ORIGINALS).iterdir():
            if candidate.name.upper() == name.upper():
                return candidate
    return path


def load_levels(numbers):
    spec = importlib.util.spec_from_file_location("uncps", UNCPS)
    uncps = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(uncps)
    levels = []
    for n in numbers:
        payload, _ = uncps.decode_cps(game_file(f"LEVEL{n}.INF").read_bytes())
        levels.append(Level(n, payload))
    return levels


def explore(level):
    """Follow control flow from every distinct nonzero binding reference."""
    buf, mo = level.buf, level.message_offset
    insns, owner, problems = {}, {}, []
    entries = sorted({ref for _, _, ref in level.bindings if ref})
    work = [("binding", e, e) for e in entries]
    seen_targets = set()

    def note(kind, at, detail=""):
        problems.append((kind, at, detail))

    while work:
        origin, pos, via = work.pop()
        while True:
            if pos < 2 or pos >= len(buf):
                note("target-outside-buffer" if via != pos else "entry-outside-buffer", via, f"{pos}")
                break
            if pos >= mo:
                note("enters-message-table", via, f"{pos}")
                break
            if pos in insns:
                break
            b = buf[pos]
            if b < 0xe2:
                insn = Insn(pos, b)
                insn.key = "SKIP"
            else:
                try:
                    insn = decode(buf, pos)
                except Truncated:
                    note("truncated-operands", pos, f"op {b:#04x}")
                    break
                except UnknownLayout as exc:
                    note("unknown-layout", pos, f"{NAMES[b]} {exc}")
                    break
            hit = [owner[p] for p in range(pos, pos + insn.length) if p in owner]
            if hit and insn.key != "SKIP":
                note("overlaps-instruction", pos, f"with {hit[0]}")
            for p in range(pos, pos + insn.length):
                owner.setdefault(p, pos)
            insns[pos] = insn
            nxt = pos + insn.length
            if insn.flow == "seq":
                pos = nxt
            elif insn.flow == "call":
                work.append(("call", insn.target, pos)); pos = nxt
            elif insn.flow == "cond":
                if getattr(insn, "depth", 1) != 1:
                    note("unbalanced-expression", pos, f"depth {insn.depth}")
                work.append(("branch", insn.target, pos)); pos = nxt
            elif insn.flow == "jump":
                via, pos = pos, insn.target
            else:
                break
    return insns, owner, problems, entries


def gaps(level, owner):
    ranges, start = [], None
    for p in range(2, level.message_offset):
        if p not in owner:
            start = p if start is None else start
        elif start is not None:
            ranges.append((start, p - 1)); start = None
    if start is not None:
        ranges.append((start, level.message_offset - 1))
    return ranges


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--listing", type=int, metavar="LEVEL")
    ap.add_argument("--gaps", type=int, metavar="LEVEL")
    ap.add_argument("--usage", action="store_true")
    ap.add_argument("--game", type=Path, metavar="DIR",
                    help="directory holding the game files (default: data/originals/eob2)")
    args = ap.parse_args()
    if args.game:
        global ORIGINALS
        ORIGINALS = args.game
    wanted = [args.listing or args.gaps] if (args.listing or args.gaps) else range(1, LEVEL_COUNT + 1)
    levels = load_levels(wanted)

    if args.listing:
        lv = levels[0]
        insns, owner, problems, entries = explore(lv)
        for pos in sorted(insns):
            i = insns[pos]
            if i.key == "SKIP":
                print(f"{pos:5d}  {i.opcode:02x}  SKIP")
            else:
                print(f"{pos:5d}  {i.opcode:02x}  {i.key} {i.text}")
        for p in problems:
            print("PROBLEM", p)
        return
    if args.gaps:
        lv = levels[0]
        insns, owner, problems, entries = explore(lv)
        for a, b in gaps(lv, owner):
            print(f"{a}-{b} ({b - a + 1} bytes) {classify_gap(lv, insns, owner, a, b)} "
                  f"first bytes {lv.buf[a:a + 8].hex(' ')}")
        return
    if args.usage:
        usage = defaultdict(Counter)
        for lv in levels:
            insns, owner, problems, entries = explore(lv)
            for i in insns.values():
                if i.key != "SKIP":
                    usage[i.key][selector_of(i, lv.buf)] += 1
        for key in sorted(usage, key=lambda k: -sum(usage[k].values())):
            sel = usage[key]
            print(f"{key:28s} {sum(sel.values()):5d}  " +
                  ("" if list(sel) == [None] else
                   ", ".join(f"{k}:{v}" for k, v in sorted(sel.items(), key=lambda kv: str(kv[0])))))
        tokens, unbalanced = Counter(), 0
        for lv in levels:
            insns, owner, problems, entries = explore(lv)
            for i in insns.values():
                if i.opcode == 0xee and i.key != "SKIP":
                    tokens.update(TOKEN_NAMES[t] for t in i.tokens)
                    unbalanced += i.depth != 1
        print("\nexpression tokens (", sum(tokens.values()), "total; unbalanced expressions:", unbalanced, ")")
        for name, n in tokens.most_common():
            print(f"  {name:36s} {n}")
        used = {k for k in usage}
        print("never decoded:", [n for b, n in sorted(NAMES.items(), reverse=True) if n not in used])
        return

    totals, problem_kinds, unknowns = Counter(), Counter(), Counter()
    gap_kinds, gap_bytes, unref = Counter(), Counter(), []
    msg_bad = 0
    sentinel = Counter()
    print("level  buf  scripts  entries  insns  covered  gaps  problems")
    for lv in levels:
        insns, owner, problems, entries = explore(lv)
        script_bytes = lv.message_offset - 2
        covered = sum(1 for p in range(2, lv.message_offset) if p in owner)
        g = gaps(lv, owner)
        for a, b in g:
            kind = classify_gap(lv, insns, owner, a, b)
            gap_kinds[kind] += 1
            gap_bytes[kind] += b - a + 1
            if kind == "unreferenced":
                unref.append((lv.number, a, b, lv.buf[a:b + 1].hex(" ")))
        for i in insns.values():
            totals[i.key] += 1
            for idx in i.message_refs:
                if idx >= lv.message_count:
                    msg_bad += 1
                    sentinel[(i.key, idx)] += 1
        for kind, at, detail in problems:
            problem_kinds[kind] += 1
            if kind == "unknown-layout":
                unknowns[detail] += 1
        print(f"{lv.number:5d} {len(lv.buf):5d} {script_bytes:8d} {len(entries):8d} "
              f"{sum(1 for i in insns.values() if i.key != 'SKIP'):6d} "
              f"{covered:7d} {len(g):5d} {len(problems):9d}")
    print()
    print("instruction counts:", dict(sorted(totals.items(), key=lambda kv: -kv[1])))
    print("problem kinds:", dict(problem_kinds))
    print("unknown layouts:", dict(unknowns))
    print("message indices outside the string table:", msg_bad, dict(sentinel))
    print("unreached ranges:", dict(gap_kinds), "bytes:", dict(gap_bytes))
    for row in unref:
        print("  unreferenced:", row)


if __name__ == "__main__":
    sys.exit(main())
