"""Turn an open :class:`mdb.MDBFile` into the JSON model the web UI consumes.

This module is the *contract* between the two halves of MDBro.  It is written
to run unchanged in two places:

* here, ahead of time, producing a static bundle for the prototype;
* later, inside Pyodide, against a file the user drops into the page.

So it must stay pure -- no filesystem, no printing, no argparse -- and it must
never import anything the browser build cannot supply.  Everything it needs is
``mdb`` and the standard library.

Design notes
------------

*The decoder is Python, always.*  Display strings are produced here rather than
in JavaScript, because pymdb is the only thing that knows what a value means.
The browser re-decodes nothing; it renders what it is given, plus raw bytes it
slices out of the original file image.

*The raw bytes ship whole.*  The page holds the entire container image, so the
hex view is the file rather than a re-encoding of it, and byte ranges owned by
no TOC entry can be shaded as such.

*Strings are pooled.*  Property and type names repeat across 117,000 entries;
interning them roughly halves the bundle.
"""
from __future__ import annotations

import datetime
from typing import Any, Dict, List, Optional

from mdb.bento import std
from mdb.core import MDBObject, UnresolvedRef
from mdb.datatypes import (MobIndexEntry, Opaque, OffsetLength, Rational,
                           SMPTELabel)
from mdb.mobid import MobID, ShortUID
from mdb.objects import (Attribute, AttributeList, BinLink, Locator,
                         MediaDescriptor, MediaStreamLink, Mob, MobReference,
                         Sequence, SourceClip, Track)

try:                                   # as a package, and as a flat script
    from .layouts import (CONTAINER_LABEL_LAYOUT, LAYOUTS, SCALAR_FORMATS,
                          TOC_ENTRY_LAYOUT)
except ImportError:                     # pragma: no cover - script invocation
    from layouts import (CONTAINER_LABEL_LAYOUT, LAYOUTS, SCALAR_FORMATS,
                         TOC_ENTRY_LAYOUT)

__all__ = ["build_model", "MODEL_VERSION"]

#: Bumped whenever the shape below changes incompatibly, so a stale bundle
#: fails loudly in the browser instead of rendering nonsense.
MODEL_VERSION = 1

#: Values longer than this are summarised rather than rendered in full.  The
#: raw bytes are still reachable -- this only bounds the *display* string.
MAX_DISPLAY = 240


# --------------------------------------------------------------------------
# value rendering
# --------------------------------------------------------------------------
#: How a decoded value should be presented.  The browser styles on this, and
#: `blob` is the one that matters: it means "pymdb could not give this a
#: meaning", which is the honest label for Avid's undocumented serialisations.
KIND_TEXT = "text"
KIND_INT = "int"
KIND_REAL = "real"
KIND_REF = "ref"
KIND_REFS = "refs"
KIND_ID = "id"
KIND_TIME = "time"
KIND_RATE = "rate"
KIND_ENUM = "enum"
KIND_BLOB = "blob"
KIND_EMPTY = "empty"
KIND_GEOM = "geom"


def _dotted(raw: bytes) -> str:
    """Bytes as dotted 32-bit groups: ``060a2b34.01010105.…``

    The convention MXF tooling uses for labels and UMIDs.  A 64-character hex
    run is unreadable; the same run in eight groups can be compared by eye
    against a spec, which is the only thing anyone does with these.
    """
    return ".".join(raw[i:i + 4].hex() for i in range(0, len(raw), 4))


def _truncate(text: str) -> str:
    return text if len(text) <= MAX_DISPLAY else text[:MAX_DISPLAY] + "…"


def _tight(mapping: Dict[str, Any]) -> Dict[str, Any]:
    """Drop absent keys.  Multiplied by 117,000 entries this is megabytes."""
    return {k: v for k, v in mapping.items() if v is not None}


def render_value(value: Any) -> Dict[str, Any]:
    """Public wrapper: see :func:`_render_value`.  Absent keys are dropped."""
    return _tight(_render_value(value))


def _render_value(value: Any) -> Dict[str, Any]:
    """One decoded value as ``{kind, text, ...}``.

    Every branch here corresponds to something :mod:`mdb.datatypes` can return.
    The fallthrough is deliberate and is *not* an error case: an ``Opaque`` is
    a value the library structurally read but could not interpret, and saying
    so plainly is more useful than inventing a rendering for it.
    """
    if value is None:
        return {"kind": KIND_EMPTY, "text": "—"}

    if isinstance(value, bool):
        return {"kind": KIND_INT, "text": "true" if value else "false"}

    if isinstance(value, int):
        return {"kind": KIND_INT, "text": str(value)}

    if isinstance(value, float):
        return {"kind": KIND_REAL, "text": repr(value)}

    if isinstance(value, str):
        return {"kind": KIND_TEXT, "text": _truncate(value), "full": len(value)}

    if isinstance(value, Rational):
        if not value.denominator:
            return {"kind": KIND_RATE, "text": "%d/0" % value.numerator}
        exact = value.numerator % value.denominator == 0
        return {"kind": KIND_RATE,
                "text": "%d/%d" % (value.numerator, value.denominator),
                "note": None if exact else "%.3f" % float(value)}

    if isinstance(value, datetime.datetime):
        return {"kind": KIND_TIME, "text": value.isoformat(sep=" ").replace("+00:00", "Z")}

    if isinstance(value, MobID):
        # the dotted UMID is the literal identity; the short UID it maps to is
        # derived, and the byte pane shows the derivation when the row is picked
        return {"kind": KIND_ID, "text": _dotted(value.bytes)}

    if isinstance(value, ShortUID):
        return {"kind": KIND_ID, "text": str(value),
                "note": "null" if value.is_null else None}

    if isinstance(value, SMPTELabel):
        return {"kind": KIND_ID, "text": _dotted(value.ul)}

    if isinstance(value, OffsetLength):
        return {"kind": KIND_GEOM,
                "text": "offset 0x%x, length 0x%x" % (value.offset, value.length)}

    if isinstance(value, UnresolvedRef):
        return {"kind": KIND_REF, "text": "0x%x" % value.object_id,
                "ref": value.object_id, "unresolved": True}

    if isinstance(value, MDBObject):
        return {"kind": KIND_REF, "text": "0x%x" % value.object_id,
                "ref": value.object_id}

    if isinstance(value, Opaque):
        # a value short enough to read *is* its bytes; a long one is a size
        raw = value.raw
        return {"kind": KIND_BLOB, "bytes": len(raw),
                "text": _dotted(raw) if 0 < len(raw) <= 16 else "%d bytes" % len(raw),
                "peek": None if len(raw) <= 16 else _dotted(raw[:8])}

    if isinstance(value, (bytes, bytearray)):
        raw = bytes(value)
        return {"kind": KIND_BLOB, "bytes": len(raw),
                "text": _dotted(raw) if 0 < len(raw) <= 16 else "%d bytes" % len(raw),
                "peek": None if len(raw) <= 16 else _dotted(raw[:8])}

    if isinstance(value, tuple) and len(value) == 2 \
            and all(isinstance(v, int) for v in value):
        return {"kind": KIND_INT, "text": "%d.%d" % value}

    if isinstance(value, list):
        if not value:
            return {"kind": KIND_EMPTY, "text": "empty list"}
        if all(isinstance(v, int) for v in value):
            return {"kind": KIND_REFS, "text": ", ".join("0x%x" % v for v in value[:12])
                    + ("…" if len(value) > 12 else ""),
                    "refs": value, "count": len(value)}
        if all(isinstance(v, MobIndexEntry) for v in value):
            return {"kind": KIND_REFS, "text": "%d index records" % len(value),
                    "refs": [v.object_id for v in value], "count": len(value)}
        if all(isinstance(v, (MDBObject, UnresolvedRef)) for v in value):
            ids = [v.object_id for v in value]
            return {"kind": KIND_REFS,
                    "text": ", ".join("0x%x" % i for i in ids[:12])
                    + ("…" if len(ids) > 12 else ""),
                    "refs": ids, "count": len(ids)}
        return {"kind": KIND_TEXT, "text": _truncate(repr(value)), "count": len(value)}

    return {"kind": KIND_BLOB, "text": _truncate(repr(value))}


# --------------------------------------------------------------------------
# string pool
# --------------------------------------------------------------------------
class _Pool(object):
    """Interns repeated strings; the bundle stores indices."""

    def __init__(self):
        self.items: List[str] = []
        self._index: Dict[str, int] = {}

    def __call__(self, text: Optional[str]) -> int:
        if text is None:
            text = ""
        found = self._index.get(text)
        if found is None:
            found = len(self.items)
            self.items.append(text)
            self._index[text] = found
        return found


# --------------------------------------------------------------------------
# objects
# --------------------------------------------------------------------------
#: Track-kind initials, the way an edit suite writes them on a timeline.
TRACK_ABBREV = {
    "picture": "V", "sound": "A", "timecode": "TC",
    "edgecode": "EC", "attribute": "AT", "effect": "FX",
}
def _label_for(obj: MDBObject) -> str:
    """A short human label -- what the row shows before you open it.

    Deliberately reuses each class's own ``_repr_extra``, so a label improves
    for free whenever pymdb learns more about a class.
    """
    try:
        # a SourceClip's own repr is the full source URN, which is too long to
        # be a row label and says less than the short UID it contains
        if isinstance(obj, SourceClip):
            source = obj.get("OMFI:SCLP:SourceID")
            short = getattr(source, "short_uid", source)
            return str(short) if short is not None else ""
        extra = obj._repr_extra()
    except Exception:
        extra = ""
    return extra or ""


def _detail_for(obj: MDBObject) -> str:
    """The one fact worth showing in the table before you open the row.

    Chosen per class rather than generically, because "the most useful single
    line" is genuinely different for a locator (its path) and for a descriptor
    (its raster and rate).  Anything that raises falls back to empty: a detail
    column is never worth failing a render over.
    """
    try:
        if isinstance(obj, Mob):
            bits = []
            d = obj.descriptor
            if d is not None:
                bits.append(d.summary())
            paths = obj.paths()
            if paths:
                bits.append(paths[0])
            elif obj.volumes():
                bits.append("on " + obj.volumes()[0])
            return "  ".join(b for b in bits if b)
        if isinstance(obj, MediaStreamLink):
            return obj.volume or ""
        if isinstance(obj, Locator):
            return obj.path or ""
        if isinstance(obj, MediaDescriptor):
            return obj.summary()
        if isinstance(obj, Track):
            return obj.track_kind_name or ""
        if isinstance(obj, Attribute):
            value = obj.value
            if isinstance(value, (str, int)):
                return "%s = %s" % (obj.name, value)
            return obj.name or ""
        if isinstance(obj, SourceClip):
            source = obj.source_mob()
            return ("-> " + (source.name or "0x%x" % source.object_id)) if source \
                else "no source"
        if isinstance(obj, AttributeList):
            return "%d attributes" % len(obj)
        if isinstance(obj, Sequence):
            return "%d components" % len(obj)
    except Exception:
        return ""
    return ""


def _track_label(obj: MDBObject) -> Optional[str]:
    """A single track's abbreviation, ``A1`` / ``V2`` / ``TC1``."""
    if not isinstance(obj, Track):
        return None
    kind = TRACK_ABBREV.get(obj.track_kind_name)
    if kind is None:
        kind = (obj.track_kind_name or "?")[:2].upper()
    number = obj.label_number
    return "%s%d" % (kind, number) if isinstance(number, int) else kind


def _umid_for(obj: MDBObject) -> Optional[str]:
    """The UMID this object carries, if it carries one.

    Mobs carry theirs directly; MSML and MCMR carry a copy of the mob's,
    which is how they link without a reference.  Everything else has none,
    and the tree fills the column in from the mob the row sits under.
    """
    for name in ("OMFI:MOBJ:MobID", "OMFI:MSML:MobID", "OMFI:MCMR:MC:MobID"):
        value = obj.get(name)
        if isinstance(value, MobID):
            return _dotted(value.bytes)
        if isinstance(value, ShortUID):
            return str(value)
    return None


def _kind_of(obj: MDBObject) -> str:
    """A coarse role tag, used for icons and for grouping."""
    if isinstance(obj, Mob):
        return "mob"
    if isinstance(obj, Track):
        return "track"
    if isinstance(obj, Sequence):
        return "sequence"
    if isinstance(obj, SourceClip):
        return "clip"
    if isinstance(obj, MediaDescriptor):
        return "descriptor"
    if isinstance(obj, MediaStreamLink):
        return "volume"
    if isinstance(obj, Locator):
        return "locator"
    if isinstance(obj, AttributeList):
        return "attrs"
    if isinstance(obj, Attribute):
        return "attr"
    if isinstance(obj, BinLink):
        return "bin"
    if isinstance(obj, MobReference):
        return "mobref"
    return "object"


def _computed_rows(obj: MDBObject, pool: _Pool) -> List[Dict[str, Any]]:
    """Rows this reader derives from an object rather than reads out of it.

    Only Mobs need it so far.  SMPTE ST 330 says a basic UMID's bytes 13-15
    are the instance number and bytes 16-31 are the 16-byte material number;
    they are the identifiers a spec-level tool asks for, and neither is
    stored under its own property name in the file.

    They are named ``OMFI:MOBJ:*`` so the grid's group-by-prefix logic
    tucks them into the MOBJ group next to MobID, which is where you
    already look for an identifier.  ``computed: 1`` still marks them so
    the byte pane knows it has no TOC entry to open.
    """
    out: List[Dict[str, Any]] = []
    if not isinstance(obj, Mob):
        return out
    mob_id = obj.get("OMFI:MOBJ:MobID")
    if not isinstance(mob_id, MobID):
        return out
    raw = mob_id.bytes
    if len(raw) < 32:
        return out
    material = raw[16:32]
    instance = int.from_bytes(raw[13:16], "big")
    out.append({
        "n": pool("OMFI:MOBJ:MaterialNumber"),
        "t": pool("SMPTE ST 330"),
        "pi": 0, "ti": 0, "e": -1, "computed": 1,
        "v": {"kind": KIND_ID, "text": _dotted(material)},
    })
    out.append({
        "n": pool("OMFI:MOBJ:InstanceNumber"),
        "t": pool("SMPTE ST 330"),
        "pi": 0, "ti": 0, "e": -1, "computed": 1,
        "v": {"kind": KIND_INT, "text": str(instance),
              "note": "0x%06x" % instance},
    })
    return out


def _insert_computed(props: List[Dict[str, Any]],
                     computed: List[Dict[str, Any]],
                     pool: _Pool) -> List[Dict[str, Any]]:
    """Place computed rows next to the property they derive from.

    The derived identifiers sit just after the last MobID row; appending
    them to the end would put them below LastModified and other bookkeeping
    fields, where they read as an afterthought.
    """
    if not computed:
        return props
    mobid_name = pool("OMFI:MOBJ:MobID")
    # Insert after the FIRST MobID row.  Duplicates fold at display time
    # keeping the first-appearance position (see fold() in inspector.js),
    # so the computed rows have to land there rather than after the last.
    for i, row in enumerate(props):
        if row.get("n") == mobid_name:
            return props[:i + 1] + computed + props[i + 1:]
    return props + computed


def _property_rows(obj: MDBObject, pool: _Pool, container) -> List[Dict[str, Any]]:
    """Every TOC entry of an object, in file order, as a property row.

    Entries rather than properties: a property written twice is two rows,
    which is the point -- duplicates are ordinary in this format and hiding
    them would misrepresent the file.  ``dup`` marks the ones an attribute
    read would not return, so the grid can grey them without dropping them.

    Property and type IDs travel with each row.  They are what the file
    actually stores; the names are a lookup through the file's own registry,
    and showing both means a row can be checked against a hex dump.
    """
    cls = type(obj)
    bound_by_omf = cls._propertydefs_by_omf
    structural = set(cls._structural_properties)
    endian = container.label.endian

    seen_counts: Dict[str, int] = {}
    for e in obj.entries:
        name = container.name_of(e.property_id)
        seen_counts[name] = seen_counts.get(name, 0) + 1
    occurrence: Dict[str, int] = {}

    from mdb import datatypes

    rows = []
    for e in obj.entries:
        name = container.name_of(e.property_id)
        type_name = container.name_of(e.type_id)
        occurrence[name] = occurrence.get(name, 0) + 1
        is_last = occurrence[name] == seen_counts[name]

        if e.property_id in std.GEOMETRY_PROPERTIES:
            value = OffsetLength(e.value, e.length)
        elif name.startswith("<std:") and e.immediate:
            value = e.value
        else:
            value = datatypes.decode(type_name, container.entry_bytes(e),
                                     endian, property_name=name)

        # A single ObjRef decodes to a bare integer, which in a grid is
        # indistinguishable from a length or a flag.  It is a pointer, so it
        # is rendered as one.
        if type_name == "omfi:ObjRef" and isinstance(value, int):
            rendered = {"kind": KIND_REF, "text": "0x%x" % value, "ref": value}
            if container.objects.get(value) is None:
                rendered["unresolved"] = True
        else:
            rendered = render_value(value)

        pdef = bound_by_omf.get(name)
        row = {
            "n": pool(name),
            "t": pool(type_name),
            "pi": e.property_id,
            "ti": e.type_id,
            "e": e.index,
            "v": rendered,
        }
        if pdef is not None and pdef.enum is not None:
            from mdb.enums import label
            row["el"] = label(pdef.enum, value, pdef.name)
        if pdef is None and name not in structural:
            # Bento's own bookkeeping is not OMF content and is not a gap in
            # the reader; only unbound OMF properties count as dark.
            row["b"] = "std" if name.startswith("<std:") else "dark"
        if not is_last:
            row["dup"] = 1
        rows.append(row)
    return rows


# --------------------------------------------------------------------------
# the mob-centric tree
# --------------------------------------------------------------------------
def _node(obj: MDBObject, role: str, children=None, note=None, jump=False):
    node = {"id": obj.object_id, "role": role}
    if children:
        node["c"] = children
    if note:
        node["note"] = note
    if jump:
        node["jump"] = 1        # a cross-link, not containment: do not recurse
    return node


def _attr_children(attrs: AttributeList, depth: int = 0) -> List[Dict[str, Any]]:
    """The ATTB tree under an ATTR, one level of nesting followed.

    Bin membership hides down here: ``ATTB('_ORG_BIN')`` holds an ``MCBR``,
    which is the only route to it because MCBR carries no MobID of its own.
    """
    out = []
    for attr in attrs:
        value = attr.value
        kids = None
        if isinstance(value, AttributeList) and depth < 3:
            kids = _attr_children(value, depth + 1)
        elif isinstance(value, MDBObject):
            kids = [_node(value, "attr-value")]
        out.append(_node(attr, "attribute", kids))
    return out


def _mob_children(mob: Mob) -> List[Dict[str, Any]]:
    """The logical anatomy of one mob.

    Order matters: tracks first because that is the question people arrive
    with, then the descriptor and its locators (where is the media), then the
    Avid attribute tree (which bin, which project).
    """
    children: List[Dict[str, Any]] = []

    for track in (mob.tracks or []):
        comp = getattr(track, "component", None)
        kids = []
        if isinstance(comp, Sequence):
            seq_kids = []
            for item in comp:
                item_kids = None
                if isinstance(item, SourceClip):
                    source = item.source_mob()
                    if source is not None:
                        item_kids = [_node(source, "source-mob", note="derives from",
                                           jump=True)]
                seq_kids.append(_node(item, "component", item_kids))
            kids.append(_node(comp, "sequence", seq_kids))
        elif isinstance(comp, MDBObject):
            item_kids = None
            if isinstance(comp, SourceClip):
                source = comp.source_mob()
                if source is not None:
                    item_kids = [_node(source, "source-mob", note="derives from",
                                       jump=True)]
            kids.append(_node(comp, "component", item_kids))
        children.append(_node(track, "track", kids))

    descriptor = mob.descriptor
    if descriptor is not None:
        loc_nodes = [_node(loc, "locator") for loc in descriptor.locators()]
        children.append(_node(descriptor, "descriptor", loc_nodes))

    attrs = mob.attribute_list()
    if attrs is not None:
        children.append(_node(attrs, "attributes", _attr_children(attrs)))

    return children


def _track_summary(mob: Mob) -> str:
    """A mob's tracks as ``V1 A1-4 TC1``.

    Consecutive numbers within a kind collapse to a range, which is the only
    way a master mob with eight audio tracks fits in a column.  Kinds keep
    their first-seen order rather than being sorted, because that is the order
    the mob declares them in.
    """
    order: List[str] = []
    groups: Dict[str, List[int]] = {}
    for track in (mob.tracks or []):
        kind = TRACK_ABBREV.get(track.track_kind_name)
        if kind is None:                       # an unmapped or absent kind
            kind = (track.track_kind_name or "?")[:2].upper()
        if kind not in groups:
            groups[kind] = []
            order.append(kind)
        number = track.label_number
        if isinstance(number, int):
            groups[kind].append(number)

    out = []
    for kind in order:
        numbers = sorted(set(groups[kind]))
        if not numbers:
            out.append(kind)
            continue
        runs, start, prev = [], numbers[0], numbers[0]
        for n in numbers[1:]:
            if n == prev + 1:
                prev = n
                continue
            runs.append((start, prev))
            start = prev = n
        runs.append((start, prev))
        out.append(" ".join(
            "%s%d" % (kind, a) if a == b else "%s%d-%d" % (kind, a, b)
            for a, b in runs))
    return " ".join(out)


def _mob_role(mob: Mob) -> str:
    """Master / source / composition, decided from the file rather than assumed."""
    if mob.descriptor is not None:
        return "source"
    if (mob.usage_code or 0) == 7:
        return "master"
    return "composition"


# --------------------------------------------------------------------------
# dark metadata
# --------------------------------------------------------------------------
def _dark_summary(f, pool: _Pool) -> Dict[str, Any]:
    """What the file says that this reader cannot fully account for.

    Two ideas, which fail differently:

    ``unbound``
        property names present in the file that pymdb has no ``PropertyDef``
        for.  The reader saw them, decoded them by type, and has no name for
        what they mean.

    ``opaque``
        entries whose value decoded to ``Opaque``: bytes with a structure but
        no interpretation.  These are the ones the property grid shows as
        raw bytes, and this is their tally.
    """
    container = f.container
    unbound: Dict[str, Dict[str, Any]] = {}
    opaque: Dict[str, Dict[str, Any]] = {}

    for obj in f.objects():
        cls = type(obj)
        known = set(cls._propertydefs_by_omf) | set(cls._structural_properties)
        cid = obj.class_name or "????"
        for name in obj.property_names():
            if name in known or name == "OMFI:ObjID" or name.startswith("<std:"):
                continue
            key = "%s\t%s" % (cid, name)
            slot = unbound.setdefault(key, {"c": cid, "n": name, "count": 0,
                                            "type": obj.type_of(name), "sample": None})
            slot["count"] += 1
            if slot["sample"] is None:
                slot["sample"] = render_value(obj.get(name))
        for name, value in obj.items():
            if isinstance(value, Opaque):
                key = "%s\t%s" % (cid, name)
                slot = opaque.setdefault(key, {"c": cid, "n": name, "count": 0,
                                               "type": value.type_name})
                slot["count"] += 1

    # An unbound property is very often also an opaque one -- the reader has
    # neither a name for it nor a decoder for its type -- so they are merged
    # into one row carrying both flags rather than listed twice.
    merged: Dict[str, Dict[str, Any]] = {}
    for key, slot in unbound.items():
        merged[key] = dict(slot, unbound=1, opaque=0)
    for key, slot in opaque.items():
        row = merged.get(key)
        if row is None:
            merged[key] = dict(slot, unbound=0, opaque=1, sample=None)
        else:
            row["opaque"] = 1

    by_type: Dict[str, int] = {}
    for slot in opaque.values():
        by_type[slot["type"] or "?"] = by_type.get(slot["type"] or "?", 0) + slot["count"]

    return {
        "rows": sorted(merged.values(),
                       key=lambda d: (-d["count"], d["c"], d["n"])),
        "byType": sorted(({"type": t, "count": n} for t, n in by_type.items()),
                         key=lambda d: -d["count"]),
        "unbound": sorted(unbound.values(), key=lambda d: -d["count"]),
        "opaque": sorted(opaque.values(), key=lambda d: -d["count"]),
    }


# --------------------------------------------------------------------------
# entry point
# --------------------------------------------------------------------------
def build_model(f, include_objects: bool = True) -> Dict[str, Any]:
    """The whole bundle.  ``f`` is an open :class:`mdb.MDBFile`."""
    container = f.container
    pool = _Pool()

    objects: Dict[str, Any] = {}
    if include_objects:
        for obj in f.objects(data_only=False):
            objects[str(obj.object_id)] = {
                "id": obj.object_id,
                "cls": obj.class_name or "",
                "py": type(obj).__name__,
                "kind": _kind_of(obj),
                "label": _label_for(obj),
                "detail": _detail_for(obj),
                "umid": _umid_for(obj),
                "trk": _track_label(obj),
                "props": _insert_computed(
                    _property_rows(obj, pool, container),
                    _computed_rows(obj, pool), pool),
                "refs": obj.referenced_ids(),
                "schema": 1 if container.is_schema(obj.object_id) else 0,
            }

    # reverse index, built once here rather than lazily in the browser
    referrers: Dict[int, List[int]] = {}
    for oid, rec in objects.items():
        for ref in rec["refs"]:
            referrers.setdefault(ref, []).append(int(oid))

    live = {m.object_id for m in f.spine_mobs}
    roots = {"master": [], "source": [], "composition": [], "deleted": []}
    tree: Dict[str, Any] = {}
    for mob in f.spine_mobs:
        role = _mob_role(mob)
        roots[role].append(mob.object_id)
        tree[str(mob.object_id)] = _mob_children(mob)
    for mob in f.mobs:
        if mob.object_id not in live:
            roots["deleted"].append(mob.object_id)
            tree[str(mob.object_id)] = _mob_children(mob)

    summary = f.summary()
    label = container.label

    return {
        "version": MODEL_VERSION,
        "meta": {
            "name": (summary["path"] or "").replace("\\", "/").split("/")[-1],
            "size": summary["size"],
            "bento": summary["bento_version"],
            "byteOrder": summary["byte_order"],
            "tocOffset": summary["toc_offset"],
            "tocSize": summary["toc_size"],
            "entries": summary["entries"],
            "objects": summary["objects"],
            "minseed": summary["minseed"],
            "seed": summary["seed"],
            "schemaNames": summary["schema_names"],
            "firstDataEntry": summary["first_data_entry"],
            "lastModified": (summary["last_modified"].isoformat(sep=" ")
                             if summary["last_modified"] else None),
            "heapEnd": label.toc_offset,
            "numDelMobs": f.header.num_del_mobs,
            "containerOffsetAtClose": f.header.container_offset_at_close,
            "tocOffsetAtClose": f.header.toc_offset_at_close,
        },
        "census": dict(f.class_census().most_common()),
        # the file's own name registry: the browser needs it to say what a
        # numeric property or type ID in a raw TOC entry actually is
        "names": {str(k): v for k, v in container.names.items()},
        "mobs": _mob_table(f),
        "classes": _class_table(f),
        "strings": pool.items,
        "objects": objects,
        "referrers": {str(k): v for k, v in referrers.items()},
        "roots": roots,
        "tree": tree,
        "dark": _dark_summary(f, pool),
        "layouts": {
            "types": LAYOUTS,
            "scalars": SCALAR_FORMATS,
            "tocEntry": TOC_ENTRY_LAYOUT,
            "containerLabel": CONTAINER_LABEL_LAYOUT,
        },
    }


def _mob_table(f) -> Dict[str, Any]:
    """Per-mob facts the table shows without opening the row."""
    live = {m.object_id for m in f.spine_mobs}
    out: Dict[str, Any] = {}
    for mob in f.mobs:
        try:
            descriptor = mob.descriptor
            out[str(mob.object_id)] = {
                "role": _mob_role(mob),
                "name": mob.name or "",
                "tracks": len(mob.tracks or []),
                "trackSummary": _track_summary(mob),
                "rate": str(mob.edit_rate) if mob.edit_rate else None,
                "length": mob.get("OMFI:TRKG:GroupLength"),
                "usage": mob.usage_code_name,
                "desc": descriptor.summary() if descriptor else None,
                "paths": mob.paths(),
                "volumes": mob.volumes(),
                "bins": mob.bins(),
                "mobId": (_dotted(mob.mob_id.bytes)
                          if mob.mob_id is not None else None),
                "shortUid": (str(mob.mob_id.short_uid)
                             if mob.mob_id is not None
                             and hasattr(mob.mob_id, "short_uid") else None),
                "live": mob.object_id in live,
            }
        except Exception:
            out[str(mob.object_id)] = {"role": "unknown", "name": "",
                                       "trackSummary": "", "live": False}
    return out


def _class_table(f) -> Dict[str, Any]:
    """Every 4CC in the file, with how pymdb resolved it and what it declares.

    ``how`` is the interesting column: ``registry`` means the library knows the
    class outright, ``inherited`` means it fell back to the nearest ancestor
    the *file's own* class dictionary declares, and ``generic`` means neither
    worked and the object is readable only by OMF property name.
    """
    from mdb.core import class_for, MDBObject
    out: Dict[str, Any] = {}
    declared = {c.class_4cc: c.parent_4cc for c in f.class_dictionary if c.class_4cc}
    for cid, count in f.class_census().items():
        cls = f.class_for_id(cid)
        if class_for(cid) is not MDBObject:
            how = "registry"
        elif cls is not MDBObject:
            how = "inherited"
        else:
            how = "generic"
        out[cid] = {
            "count": count,
            "py": cls.__name__,
            "how": how,
            "parent": declared.get(cid),
            "known": sorted(set(cls._propertydefs_by_omf)
                            | set(cls._structural_properties)),
        }
    for cid, parent in declared.items():
        if cid not in out:
            cls = f.class_for_id(cid)
            out[cid] = {"count": 0, "py": cls.__name__,
                        "how": "declared-unused", "parent": parent,
                        "known": sorted(set(cls._propertydefs_by_omf))}
    # Abstract bases the reader knows (``CPNT``, ``TRKG``, ``CLIP``, …) rarely
    # get instances of their own and rarely appear in the file's class
    # dictionary either, but their 4CCs show up as name-prefixes on every
    # object -- ``OMFI:CPNT:Name`` on any Component subclass, for one.  The
    # grid needs their human names to label its groups.
    from mdb.core import CLASS_REGISTRY
    for cid, cls in CLASS_REGISTRY.items():
        if cid and cid not in out:
            out[cid] = {"count": 0, "py": cls.__name__,
                        "how": "abstract", "parent": None,
                        "known": sorted(set(cls._propertydefs_by_omf))}
    return out
