"""Free, local MTG Arena collection exporter (memory-based).

Modern MTG Arena no longer writes the player's collection to ``Player.log``
(verified: a fresh login logs only home-screen calls — no
``PlayerInventory.GetPlayerCards``), so log-scraping tools cannot read it. This
tool reads the collection straight out of the running ``MTGA.exe`` process,
which is log-independent and always current.

How it works
------------
MTGA holds the collection in memory as a flat array of
``(grpId: uint32, quantity: uint32)`` little-endian pairs. We:

1. Build a ``grpId -> {name, set, collector}`` map from the client's OWN local
   card database (``MTGA_Data/Downloads/Raw/*.mtga`` SQLite — ``Cards`` +
   ``Localizations``), so names always match the installed client (incl. the
   newest sets). Falls back to Scryfall ``arena_id`` bulk data if needed.
2. Walk every committed, writable memory region of ``MTGA.exe`` looking for the
   longest contiguous run of *valid* ``(grpId, qty)`` pairs, and disambiguate
   by which candidate block's grpIds best resolve against the name map. That
   block is the collection.
3. Write ``mtga_collection.txt`` — bare ``N CardName`` lines, ready to paste
   into Tutorbox's "Import Arena List" (set/collector are intentionally omitted;
   Arena ownership is per-card). Also writes ``mtga_collection.json`` (the full
   per-printing rows).

Only reads memory + local files (and optionally Scryfall for names); writes only
local output files. It does not modify the game. Run it with Arena open and on
the Decks/Collection screen.

NOTE: reading game memory is against MTGA's ToS in the strict letter (like every
collection tracker). It only ever reads YOUR OWN collection for personal use.

Usage::

    pip install pymem requests
    python tools/arena_collection_exporter.py
    # optional disambiguation if auto-detect picks the wrong block:
    python tools/arena_collection_exporter.py --anchor "Sol Ring:1" --anchor "Llanowar Elves:4"

Regenerating the server's card map (maintainers, from a repo checkout)
----------------------------------------------------------------------
The server resolves Arena card ids to names from ``backend/game/arena_card_map.json``.
It is generated from the same local client DB, so ``--dump-card-map`` rebuilds it
without attaching to the game or touching the network::

    python tools/arena_collection_exporter.py --dump-card-map backend/game/arena_card_map.json
    # client installed somewhere else:  --db "<dir>/Raw_CardDatabase_<hash>.mtga"

The output is the flat ``{"<grpId>": "<name>"}`` object the server reads, keys
sorted numerically so a re-run on the same client build is byte-identical,
followed by one newline, which the repo's end-of-file-fixer hook requires. No
card-content filter is applied, so any ``A-`` rebalanced names and tokens the
client DB holds are written. A ``Cards`` row whose title has no English text is
not written, and neither is one a card map cannot hold (a negative or
non-integer GrpId, a non-text name); the dump prints how many of the latter it
skipped. It refuses to write an empty map, and refuses to replace an existing
file that has more entries unless ``--force-shrink`` is given. It prints the
database it read and the entry count: put that line in the commit message.

The pure parsing helpers (``parse_card_pairs``, ``pick_best_block``,
``format_txt``) are import-safe on any OS and unit-tested; the memory scan
imports its Windows-only deps lazily. The client-DB read is stdlib ``sqlite3``
and is exercised in CI against a fabricated DB.
"""
from __future__ import annotations

import argparse
import json
import os
import struct
import sys
import tempfile
from pathlib import Path

# Valid bounds for a (grpId, quantity) pair in the collection array. Arena grpIds
# are ~16xxx..1xxxxx; a singleton format caps real ownership ~4, but basics and
# some promos go higher — keep generous to avoid dropping the array's tail.
_GRPID_MIN, _GRPID_MAX = 1000, 999_999
_QTY_MIN, _QTY_MAX = 1, 1000
# A run shorter than this is noise, not a collection (a real account owns 100s).
_MIN_BLOCK = 60
# Tolerate this many invalid pairs inside a run before splitting it (the array
# can be interleaved with small gaps / alignment slack).
_MISS_TOLERANCE = 8


def parse_card_pairs(data: bytes) -> list[dict[int, int]]:
    """Find runs of valid ``(grpId, qty)`` uint32 pairs in a raw byte buffer.

    Returns a list of ``{grpId: qty}`` blocks. Tries both 4-byte alignments so
    a pair that starts on an odd word boundary is still found. Pure function —
    no process access — so it is unit-testable with synthetic bytes.
    """
    n = len(data) // 4
    if n < 2:
        return []
    ints = struct.unpack(f"<{n}I", data[: n * 4])

    blocks: list[dict[int, int]] = []
    for offset in (0, 1):
        current: dict[int, int] = {}
        misses = 0
        for i in range(offset, n - 1, 2):
            k, v = ints[i], ints[i + 1]
            if _GRPID_MIN <= k <= _GRPID_MAX and _QTY_MIN <= v <= _QTY_MAX:
                current[k] = v
                misses = 0
            else:
                misses += 1
                if misses > _MISS_TOLERANCE:
                    if len(current) >= _MIN_BLOCK:
                        blocks.append(current)
                    current = {}
                    misses = 0
        if len(current) >= _MIN_BLOCK:
            blocks.append(current)
    return blocks


def pick_best_block(
    blocks: list[dict[int, int]],
    name_map: dict[int, dict] | None = None,
    anchors: dict[int, int] | None = None,
) -> dict[int, int]:
    """Choose the block most likely to be the real collection.

    Priority:
      1. If ``anchors`` (grpId->qty the user confirmed owning) are given, prefer
         a block that contains every anchor at the right quantity.
      2. Else score by ``size * name-resolution-rate`` — the collection's grpIds
         resolve against ``name_map`` far better than a random int array does.
      3. Else the largest block.
    """
    if not blocks:
        return {}
    if anchors:
        hits = [b for b in blocks
                if all(b.get(a) == q for a, q in anchors.items())]
        if hits:
            return max(hits, key=len)
    if name_map:
        def score(b: dict[int, int]) -> float:
            known = sum(1 for g in b if g in name_map)
            return known * (known / max(1, len(b)))  # size * hit-rate
        return max(blocks, key=score)
    return max(blocks, key=len)


def aggregate(collection: dict[int, int], name_map: dict[int, dict]) -> list[dict]:
    """Map grpId->name and sum quantities per (name, set). Unknown grpIds are
    kept under a ``grp:<id>`` placeholder name so nothing is silently dropped."""
    out: dict[tuple, dict] = {}
    for grp, qty in collection.items():
        info = name_map.get(grp)
        name = info["name"] if info else f"grp:{grp}"
        setc = (info.get("set") if info else "") or ""
        key = (name, setc)
        row = out.setdefault(key, {"count": 0, "name": name, "set": setc,
                                   "cn": (info or {}).get("collector_number", ""),
                                   "known": info is not None})
        row["count"] += qty
    return sorted(out.values(), key=lambda r: (r["name"], r["set"]))


def format_txt(rows: list[dict], *, include_unknown: bool = False) -> str:
    """Bare ``N CardName`` per line — the format Tutorbox's Import Arena List
    accepts. Set/collector dropped on purpose (Arena ownership is per-card), and
    quantities are summed across printings so each card appears once."""
    by_name: dict[str, int] = {}
    for r in rows:
        if not r["known"] and not include_unknown:
            continue
        by_name[r["name"]] = by_name.get(r["name"], 0) + r["count"]
    return "\n".join(f"{q} {n}" for n, q in sorted(by_name.items()))


# --------------------------------------------------------------------------
# The local card DB (stdlib sqlite3, though the install search below is
# Windows paths) and the process-memory scan (Windows-only). Lazy imports so
# the module (and its pure helpers above) import cleanly on Linux/CI.
# --------------------------------------------------------------------------

def _local_db_paths() -> list[Path]:
    return [
        Path(r"C:\Program Files\Wizards of the Coast\MTGA\MTGA_Data\Downloads\Raw"),
        Path(r"C:\Program Files (x86)\Wizards of the Coast\MTGA\MTGA_Data\Downloads\Raw"),
        Path(r"C:\Program Files (x86)\Steam\steamapps\common\MTGA\MTGA_Data\Downloads\Raw"),
    ]


def _find_local_db() -> Path | None:
    """The biggest ``Raw_CardDatabase_*.mtga`` under a known install, if any."""
    raw = next((p for p in _local_db_paths() if p.exists()), None)
    found = None
    if raw:
        found = next(iter(sorted(raw.glob("Raw_CardDatabase_*.mtga"),
                                 key=lambda f: f.stat().st_size, reverse=True)),
                     None)
    return found


def _ro_uri(db: Path) -> str:
    """A read-only SQLite URI for ``db``.

    Built with ``as_uri`` because a raw ``file:{db}`` lets ``#``, ``?`` and a
    ``%HH`` in the path be read as URI syntax, which opens a different file and
    drops ``mode=ro``. The Windows install paths have spaces and parentheses.

    ``absolute`` rather than ``resolve``: on Windows ``resolve`` turns a mapped
    drive into its UNC path, and ``file://host/share/...`` is an authority
    SQLite rejects. A UNC path given directly is not supported; map it to a
    drive or copy the database. ``absolute`` keeps any ``..`` as given, which is
    the path the existence probes asked about; only a path it leaves relative
    (``as_uri`` would raise) is completed by ``abspath``.
    """
    path = Path(db).absolute()
    if not path.is_absolute():
        path = Path(os.path.abspath(db))
    return path.as_uri() + "?mode=ro"


def _printable(exc: BaseException) -> str:
    """``exc`` with every non-printable character escaped, so text quoted from a
    third-party file cannot reach the terminal as control sequences. SQLite's
    schema errors quote the file."""
    return "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii")
                   for c in str(exc))


def _read_card_map(db: Path, lookup: dict[int, dict]) -> bool:
    """Fill ``lookup`` from the client DB at ``db``, read-only.

    False when ``db`` lacks the ``Cards`` / ``Localizations_enUS`` tables (it is
    some other SQLite file). ``sqlite3.Error`` propagates with ``lookup``
    holding whatever was read first: ``load_local_card_map`` keeps that partial
    result, the dump mode refuses it.
    """
    import sqlite3

    conn = sqlite3.connect(_ro_uri(db), uri=True)
    try:
        cur = conn.cursor()
        tables = {r[0] for r in cur.execute(
            "SELECT name FROM sqlite_master WHERE type='table'")}
        usable = "Cards" in tables and "Localizations_enUS" in tables
        if usable:
            loc: dict[int, str] = {}
            for lid, fmt, text in cur.execute(
                    "SELECT LocId, Formatted, Loc FROM Localizations_enUS"):
                if text and (lid not in loc or fmt == 0):
                    loc[lid] = text
            cols = {r[1] for r in cur.execute("PRAGMA table_info(Cards)")}
            sset = "ExpansionCode" if "ExpansionCode" in cols else "NULL"
            for grp, title, setc in cur.execute(
                    f"SELECT GrpId, TitleId, {sset} FROM Cards"):
                nm = loc.get(title)
                if nm:
                    lookup[grp] = {"name": nm, "set": setc or "",
                                   "collector_number": ""}
    finally:
        conn.close()
    return usable


def load_local_card_map(db_path: Path | str | None = None) -> dict[int, dict]:
    """grpId -> {name, set, collector_number} from the client's local SQLite.

    Modern MTGA splits the data: ``Cards`` (GrpId, TitleId, ExpansionCode) lives
    in ``Raw_CardDatabase_*.mtga`` alongside per-language name tables
    ``Localizations_enUS`` (LocId, Formatted, Loc). A LocId can have both a
    Formatted=1 (markup) and Formatted=0 (plain) row; for names they're equal,
    so we prefer Formatted=0 and accept 1 as a fallback.

    ``db_path`` names the DB file directly; without it the known install
    locations are searched.
    """
    import sqlite3

    db = Path(db_path) if db_path else _find_local_db()
    lookup: dict[int, dict] = {}
    if db is not None:
        try:
            _read_card_map(db, lookup)
        except sqlite3.Error:
            # A partial read is kept: the install search tolerates a half-read
            # DB, and main() falls back to Scryfall only when nothing was read.
            pass
    return lookup


def _load_explicit_db(db: Path) -> tuple[dict[int, dict], str | None]:
    """The card map from the DB the user named, and why not when it has none.

    Unlike ``load_local_card_map`` this keeps no partial read and says what went
    wrong, with the SQLite error escaped (see ``_printable``).
    """
    import sqlite3

    name_map: dict[int, dict] = {}
    problem = None
    try:
        if not db.is_file():
            problem = f"{db} is not a file"
        else:
            _read_card_map(db, name_map)
            if not name_map:
                problem = (f"{db} has no readable card names "
                           "(not a card database, or empty)")
    except sqlite3.Error as exc:
        name_map = {}
        problem = f"could not read {db}: {_printable(exc)}"
    except OSError as exc:
        problem = f"cannot access {db}: {_printable(exc)}"
    return name_map, problem


def build_card_map_json(name_map: dict[int, dict]) -> str:
    """The flat ``{"<grpId>": "<name>"}`` text the server's card map holds.

    Default ``json.dumps`` settings on purpose: the committed map is this shape
    (ASCII-escaped, no indent), so a regeneration differs from it only in
    content, key order and the one trailing newline the repo's end-of-file-fixer
    hook adds to any file it touches. The names come from a third-party DB and
    are only ever serialised here, never interpreted.
    """
    body = json.dumps({str(gid): name_map[gid]["name"] for gid in sorted(name_map)})
    return body + "\n"


def _storable(name_map: dict) -> dict:
    """The rows of ``name_map`` a card map can hold: a non-negative integer id
    and a text name. A negative id would be written as a key the overwrite guard
    rejects, locking the next run out of its own output, and a non-text name
    (a blob) would crash ``json.dumps``."""
    return {gid: row for gid, row in name_map.items()
            if isinstance(gid, int) and gid >= 0 and isinstance(row["name"], str)}


def _existing_map_entries(out: Path) -> int | None:
    """Entries in the card map already at ``out``; None when there is no file.

    ValueError when the file is not a card map at all, so pointing ``--dump-card-map``
    at the wrong path (a ``package.json``, say) cannot overwrite it.
    """
    count = None
    if out.exists():
        try:
            data = json.loads(out.read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise ValueError(f"{out} exists but cannot be read as JSON ({exc})") from exc
        if not (isinstance(data, dict)
                and all(isinstance(k, str) and k.isdigit() and isinstance(v, str)
                        for k, v in data.items())):
            raise ValueError(f"{out} exists but is not a grpId -> name card map")
        count = len(data)
    return count


def _write_atomic(path: Path, data: bytes) -> None:
    """Write ``data`` to ``path`` so a reader sees the old file or the new one."""
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
    try:
        with os.fdopen(fd, "wb") as fh:
            fh.write(data)
            fh.flush()
            os.fsync(fh.fileno())
        # mkstemp creates the file 0600; a repo file should not end up that way.
        os.chmod(tmp, 0o644)
        os.replace(tmp, path)
    except BaseException:
        Path(tmp).unlink(missing_ok=True)
        raise


def dump_card_map(out: Path, db_path: Path | str | None = None,
                  force_shrink: bool = False) -> int:
    """Write the client DB's grpId -> name map to ``out``; returns an exit code.

    0 written; 2 no usable client DB; 3 nothing read from it; 4 would clobber a
    file that is not a card map, or has more entries; 5 ``out`` is not writable.
    """
    import sqlite3

    try:
        if out.is_dir() or not out.parent.is_dir():
            print(f"ERROR: {out} is not a writable file path (its directory must exist).")
            return 5
        existing = _existing_map_entries(out)
    except ValueError as exc:
        print(f"ERROR: {exc}. Remove it or choose another path.")
        return 4
    except OSError as exc:
        print(f"ERROR: cannot access {out}: {_printable(exc)}")
        return 5

    db = Path(db_path) if db_path else _find_local_db()
    if db is None:
        print("ERROR: client card database not found in a standard install "
              "location. Pass --db <path to Raw_CardDatabase_*.mtga>.")
        return 2
    try:
        is_file = db.is_file()
    except OSError as exc:
        print(f"ERROR: cannot access {db}: {_printable(exc)}")
        return 2
    if not is_file:
        print(f"ERROR: {db} is not a file. Pass --db <path to "
              "Raw_CardDatabase_*.mtga>.")
        return 2
    name_map: dict[int, dict] = {}
    try:
        usable = _read_card_map(db, name_map)
    except sqlite3.Error as exc:
        print(f"ERROR: could not read {db}: {_printable(exc)}")
        return 2
    if not usable:
        print(f"ERROR: {db} has no Cards / Localizations_enUS tables; "
              "is it Raw_CardDatabase_*.mtga?")
        return 2
    read = len(name_map)
    name_map = _storable(name_map)
    if len(name_map) < read:
        print(f"  skipped {read - len(name_map)} rows with a negative or "
              "non-integer GrpId or a non-text name.")
    if not name_map:
        print(f"ERROR: read no card names from {db}; nothing written.")
        return 3
    if existing is not None and len(name_map) < existing and not force_shrink:
        print(f"ERROR: {out} has {existing} entries and this dump has "
              f"{len(name_map)}; a smaller map usually means a partial or "
              "different client DB. Pass --force-shrink to replace it anyway.")
        return 4

    try:
        _write_atomic(out, build_card_map_json(name_map).encode("ascii"))
    except OSError as exc:
        print(f"ERROR: could not write {out}: {exc}")
        return 5
    print(f"Wrote {len(name_map)} entries "
          f"({len({v['name'] for v in name_map.values()})} distinct names) "
          f"from {db} to {out}")
    return 0


def fetch_scryfall_card_map() -> dict[int, dict]:
    """Fallback grpId(arena_id) -> name from Scryfall bulk data."""
    import requests

    # Scryfall now requires a descriptive User-Agent + Accept header.
    hdrs = {"User-Agent": "TutorboxArenaExporter/1.0", "Accept": "application/json"}
    meta = requests.get(
        "https://api.scryfall.com/bulk-data/default-cards",
        headers=hdrs, timeout=30).json()
    cards = requests.get(meta["download_uri"], headers=hdrs, timeout=180).json()
    out: dict[int, dict] = {}
    for c in cards:
        aid = c.get("arena_id")
        if aid:
            out[int(aid)] = {"name": c.get("name", "Unknown"),
                             "set": (c.get("set") or "").upper(),
                             "collector_number": c.get("collector_number", "")}
    return out


def _iter_readable_regions(handle):
    """Yield (base, size) for committed, writable, non-guard regions."""
    import ctypes
    from ctypes import wintypes

    class MBI(ctypes.Structure):
        _fields_ = [
            ("BaseAddress", ctypes.c_void_p), ("AllocationBase", ctypes.c_void_p),
            ("AllocationProtect", wintypes.DWORD), ("__align", wintypes.DWORD),
            ("RegionSize", ctypes.c_size_t), ("State", wintypes.DWORD),
            ("Protect", wintypes.DWORD), ("Type", wintypes.DWORD),
        ]

    VirtualQueryEx = ctypes.windll.kernel32.VirtualQueryEx
    VirtualQueryEx.restype = ctypes.c_size_t
    MEM_COMMIT = 0x1000
    PAGE_GUARD = 0x100
    # Writable protections — the collection lives on the managed heap (RW).
    WRITABLE = {0x04, 0x08, 0x40, 0x80}  # READWRITE/WRITECOPY/EXEC_RW/EXEC_WC
    addr = 0
    mbi = MBI()
    while VirtualQueryEx(handle, ctypes.c_void_p(addr), ctypes.byref(mbi),
                         ctypes.sizeof(mbi)):
        base = mbi.BaseAddress or 0
        size = mbi.RegionSize
        if (mbi.State == MEM_COMMIT and (mbi.Protect & 0xFF) in WRITABLE
                and not (mbi.Protect & PAGE_GUARD)):
            yield base, size
        nxt = base + size
        if nxt <= addr:
            break
        addr = nxt


def scan_process_collection(proc_name: str = "MTGA.exe",
                            name_map: dict[int, dict] | None = None,
                            anchors: dict[int, int] | None = None,
                            max_region: int = 256 * 1024 * 1024) -> dict[int, int]:
    """Attach to the process and return the best ``{grpId: qty}`` block."""
    import pymem

    pm = pymem.Pymem(proc_name)
    candidates: list[dict[int, int]] = []
    for base, size in _iter_readable_regions(pm.process_handle):
        if size > max_region:
            continue
        try:
            data = pm.read_bytes(base, size)
        except Exception:
            continue
        candidates.extend(parse_card_pairs(data))
    return pick_best_block(candidates, name_map=name_map, anchors=anchors)


def _parse_anchor(spec: str, name_index: dict[str, int]) -> tuple[int, int] | None:
    name, _, qty = spec.rpartition(":")
    if not name or not qty.strip().isdigit():
        return None
    grp = name_index.get(name.strip().lower())
    return (grp, int(qty)) if grp else None


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="Export your MTG Arena collection.")
    ap.add_argument("--process", help="the game's process name (default MTGA.exe)")
    ap.add_argument("--out", help="output directory (default .)")
    ap.add_argument("--anchor", action="append", default=[],
                    help='"Card Name:Quantity" you own, to disambiguate (repeatable)')
    ap.add_argument("--include-unknown", action="store_true",
                    help="also emit cards whose grpId didn't resolve to a name")
    ap.add_argument("--db", metavar="PATH",
                    help="the client's Raw_CardDatabase_*.mtga, if it is not in a "
                         "standard install location")
    ap.add_argument("--dump-card-map", metavar="OUT",
                    help="maintainers: write the grpId -> name map to OUT (the "
                         "server's arena_card_map.json) and exit; does not read "
                         "Arena's memory or use the network. Keys are sorted "
                         "numerically")
    ap.add_argument("--force-shrink", action="store_true",
                    help="with --dump-card-map: replace an existing map even if "
                         "the new one has fewer entries")
    args = ap.parse_args(argv)

    for flag, value in (("--dump-card-map", args.dump_card_map), ("--db", args.db)):
        if value is not None and not value.strip():
            ap.error(f"{flag} needs a path")
    if args.force_shrink and args.dump_card_map is None:
        ap.error("--force-shrink only applies to --dump-card-map")
    if args.dump_card_map is not None:
        ignored = [f"--{name.replace('_', '-')}"
                   for name in ("out", "process", "anchor", "include_unknown")
                   if getattr(args, name) not in (None, [], False)]
        if ignored:
            ap.error(f"{', '.join(ignored)}: not used by --dump-card-map")
        return dump_card_map(Path(args.dump_card_map), args.db, args.force_shrink)

    print("Loading card database (local client DB)…")
    if args.db is not None:
        name_map, problem = _load_explicit_db(Path(args.db))
        if problem:
            print(f"ERROR: {problem}; not falling back to Scryfall for an "
                  "explicit --db.")
            return 2
    else:
        name_map = load_local_card_map()
    if not name_map:
        print("No card names read from a local client database (none in a "
              "standard install location, or it could not be read). Pass --db "
              "<path to Raw_CardDatabase_*.mtga> if Arena is installed "
              "elsewhere. Trying Scryfall for names…")
        try:
            name_map = fetch_scryfall_card_map()
        except Exception as e:
            print(f"Scryfall fetch failed: {e}")
            name_map = {}
    print(f"  {len(name_map)} card names loaded.")

    name_index = {v["name"].lower(): k for k, v in name_map.items()}
    anchors: dict[int, int] = {}
    for spec in args.anchor:
        pa = _parse_anchor(spec, name_index)
        if pa:
            anchors[pa[0]] = pa[1]
        else:
            print(f"  (ignored unrecognized anchor: {spec!r})")

    process = args.process or "MTGA.exe"
    print(f"Attaching to {process} and scanning memory…")
    try:
        collection = scan_process_collection(
            process, name_map=name_map, anchors=anchors or None)
    except Exception as e:
        print(f"ERROR: could not read {process}: {e}")
        print("Is Arena running? Open it to the Decks/Collection screen, then retry.")
        return 2

    if not collection:
        print("No collection block found. Try adding --anchor \"Card You Own:Qty\".")
        return 3

    rows = aggregate(collection, name_map)
    known = [r for r in rows if r["known"]]
    txt = format_txt(rows, include_unknown=args.include_unknown)

    out_dir = Path(args.out or ".")
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "mtga_collection.txt").write_text(txt + "\n", encoding="utf-8")
    (out_dir / "mtga_collection.json").write_text(
        json.dumps(rows, indent=2), encoding="utf-8")

    total = sum(r["count"] for r in known)
    print(f"\nDone: {len(known)} distinct cards ({total} total), "
          f"{len(rows) - len(known)} unresolved grpIds.")
    print(f"Wrote {out_dir / 'mtga_collection.txt'}")
    print("Upload that .txt via Tutorbox -> 'Import Arena List'.")
    return 0


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