#!/usr/bin/env python3
"""index_library.py — one deduped index of every clip this project already has.

Why this exists. On a real film the best shot for a window is often one you already
own: an earlier pass, a re-render you rejected for a different window, or something
still sitting in the provider account. On the WICC anthem, choosing from the whole
history beat rendering fresh outright — three of the strongest windows came from clips
that were already on disk. Nothing in this skill could see them, because the cut stage
globbed a single output directory.

This walks every place a usable clip can live, dedupes by content, probes each one, and
writes a contact strip so the next stage can judge PICTURES rather than filenames.

Two decisions here are load-bearing and were both bugs in the one-off original:

  * **Strips are named by content hash, not by index id.** Ids came from sort order, so
    adding one clip renumbered everything and every cached strip silently became a
    picture of a DIFFERENT clip.
  * **`--ids` is a persistent ledger.** Ids are minted for new hashes only and never
    reassigned. Without it, re-indexing invalidates every `clipId` in an already
    authored cut file.

Usage:
  index_library.py --project <P> --slug <SLUG> [--source PATH[:ORIGIN]]... [--aspect 9:16]
Exit 0 = indexed · 2 = bad input.
"""
from __future__ import annotations

import argparse
import glob
import hashlib
import html
import json
import os
import re
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lane_nav import inject_nav  # noqa: E402
from lane_page import page as shell  # noqa: E402

# Descending trust: a clip a human installed beats one a lane happened to emit.
# Every entry is derived from the project dir, so this list is pack-agnostic, and a
# path that does not exist is skipped rather than erroring — which is what lets one
# default list serve every pack.
DEFAULT_SOURCES = [
    ("build/picks", "operator-pick"),
    ("build/queue/*/clips", "queue"),
    ("build/library", "provider-account"),
    # Where a BULK pull from the provider account lands. Measured on Great Indian
    # Summer: 51 of its 78 clips sat here and the indexer never saw one of them,
    # because only the per-queue clip dirs were listed. That defeats the entire
    # premise of this script — "choose from everything you already own" — and it
    # fails silently, as a smaller candidate list rather than an error. Three of
    # that film's strongest windows came from exactly this pile.
    ("build/harvest", "harvest"),
    ("build/harvest-by-window/*", "harvest"),
    ("build/hero-*.mp4", "hero"),
    ("outputs", "lane-c"),
    ("build/broll*", "broll"),
    # EVERYTHING WE EVER RENDERED. Parked draws and the archives of earlier cuts are
    # as real as tonight's landings: a take refused on a window that no longer exists
    # may fit the window that replaced it (operator, 2026-08-22: "always create a
    # database of the videos you have, with transcripts, so nothing is wasted").
    ("build/queue/*/superseded", "parked"),
    ("build/queue-archive/*/clips", "archive"),
    ("build/queue-archive/*/superseded", "archive-parked"),
    ("build/queue-archive/*/*.mp4", "archive-parked"),
]

# `final/videos` is NEVER a source. The one-off excluded its own master by a hardcoded
# substring; generalised, the rule is that a rendered deliverable can never be a
# candidate clip for a window inside itself.
DEFAULT_EXCLUDES = ["*-FILM.mp4", "norm-*.mp4", "seg-*.mp4", "concat-*.mp4",
                    "*/segments/*", "*/_archive_invalid/*"]

ASPECTS = {"9:16": 9 / 16, "16:9": 16 / 9, "1:1": 1.0, "4:5": 4 / 5, "2:3": 2 / 3}


def die(msg: str) -> None:
    print(f"index_library: {msg}", file=sys.stderr)
    raise SystemExit(2)


def probe(rec: dict) -> dict | None:
    """ffprobe one clip. Returns None on junk — a half-downloaded mp4 probes as
    garbage, and those are counted in the summary rather than vanishing silently."""
    p = rec["clip"]
    r = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "stream=width,height,codec_type",
         "-show_entries", "format=duration", "-of", "json", p], capture_output=True)
    try:
        d = json.loads(r.stdout)
        streams = d.get("streams") or []
        v = next(s for s in streams if s.get("codec_type") == "video")
        rec["seconds"] = round(float(d["format"]["duration"]), 3)
        rec["w"], rec["h"] = int(v["width"]), int(v["height"])
        rec["hasAudio"] = any(s.get("codec_type") == "audio" for s in streams)
    except Exception:
        return None
    if rec["seconds"] <= 0 or not rec["w"] or not rec["h"]:
        return None
    st = os.stat(p)
    rec["bytes"], rec["mtime"] = st.st_size, round(st.st_mtime, 3)
    # Head hash is a fast pre-filter only; identical container headers across a
    # provider's renders are plausible, so the identity key adds size and duration.
    with open(p, "rb") as fh:
        rec["hash"] = hashlib.md5(fh.read(400_000)).hexdigest()[:12]
    return rec


def strip(rec: dict, strips_dir: str, max_tiles: int, width: int) -> None:
    """EVERY SECOND of the clip, side by side, in one ffmpeg pass.

    This used to take three frames at 15%, 50% and 85%, and that sampling is what let
    a whole class of defect through. Sync, lyric coverage and correlation are all deaf
    to PHYSICS — a bat hanging in mid-air, a stump materialising out of a hand, extra
    figures walking in from the frame edges — and on the film where that happened the
    walkers only appeared around the four-second mark. Three samples of an eight-second
    clip can show a prop shouldered at 1.2s and shouldered again at 6.8s while missing
    the moment in between where it teleported there. Eight samples show the whole move.

    `fps=1,tile=Nx1` does it in ONE pass rather than N seeks plus an hstack, so it is
    also faster than what it replaces: 0.30s against 0.69s on a real 8s clip.

    The tile count is in the FILENAME. It is part of what the image shows, so a cached
    strip from a different density must not be reused — that is how a 'fixed' QC surface
    keeps displaying the old evidence.
    """
    tiles = max(3, min(max_tiles, int(round(rec["seconds"] or 0)) or 3))
    out = os.path.join(strips_dir, f"{rec['hash']}-{tiles}f.jpg")
    rec["strip"] = out
    rec["stripTiles"] = tiles
    if os.path.isfile(out):
        return
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", rec["clip"],
                    "-vf", f"fps=1,scale={width}:-1,tile={tiles}x1",
                    "-frames:v", "1", "-q:v", "3", out], check=False)


def load_provenance(project: str) -> dict:
    """Render provenance written by explore_queue.py at submit time.

    This is what makes `synced` DECIDABLE downstream. A contact strip can show that a
    mouth is open; only the record of which bar a clip was rendered against can show
    that it is open to the right words."""
    out = {}
    for f in glob.glob(os.path.join(project, "build/queue/*/provenance.json")):
        try:
            for job, meta in json.load(open(f, encoding="utf-8")).items():
                clip = meta.get("clip")
                if clip:
                    out[os.path.realpath(clip)] = meta
        except Exception:
            continue
    # The lane driver's own record (`<id>-live-job.json`, queue AND archives) is the
    # second source: it names the window, the style and — since 2026-08-22 — the face
    # (`performer`). Every take in the same dir tree that carries the window's id
    # (clips/wNN.mp4, superseded/wNN-draw2-*.mp4, wNN-*.mp4) inherits it. provenance.json
    # wins where both exist.
    # ... and the B-roll plan's own queue (build/broll): a cutaway's record names its
    # world, and select_cut.fill_gaps prefers a gap's own world by it — unscanned, every
    # cutaway indexed world-less and the preference never fired (2026-09-02).
    for f in (glob.glob(os.path.join(project, "build/queue/*/*-live-job.json"))
              + glob.glob(os.path.join(project, "build/queue-archive/*/*-live-job.json"))
              + glob.glob(os.path.join(project, "build/broll/*-live-job.json"))):
        try:
            rec = json.load(open(f, encoding="utf-8"))
        except Exception:
            continue
        wid = rec.get("window")
        if not wid:
            continue
        meta = {k: rec[k] for k in ("styleId", "performer", "startSec", "seconds") if rec.get(k) is not None}
        meta["jobId"] = wid
        # Downstream (select_cut, review_board) reads `window` as the INDEX, the way
        # provenance.json writes it — so "w04" becomes 4 here and a B-roll id stays
        # out of the field (it was never a window).
        if re.fullmatch(r"w\d+", wid):
            meta["window"] = int(wid[1:])
        root = os.path.dirname(f)
        for pattern in (f"clips/{wid}.mp4", f"superseded/{wid}-*.mp4", f"{wid}-*.mp4", f"{wid}.mp4"):
            for clip in glob.glob(os.path.join(root, pattern)):
                out.setdefault(os.path.realpath(clip), meta)
    return out


def fit_table(rows: list[dict], plan_path: str, brief_path: str, song: str) -> None:
    """Per clip: which CURRENT windows it fits, judged the way the driver judges — only
    the seconds where that window's face sings (own spans), envelope correlation + offset.
    `faceOk` is True/False when the clip's origin style is known (provenance), else None.
    This is the suggestion the operator asked for: reuse is a click, not a memory."""
    from check_sync import best_offset
    from sync_profile import envelope
    plan = json.load(open(plan_path, encoding="utf-8"))
    brief = {w["id"]: w for w in json.load(open(brief_path, encoding="utf-8")).get("windows", [])}
    prons = [x.strip() for x in (plan.get("pronouns") or "he").split("|")]
    # a letter-tagged sheet (two boys) names the performer as the voice: a/b, not a gender
    letters = any(sp.get("who") in ("a", "b") for w in brief.values() for sp in w.get("spans", []))

    def face_of(perf):
        if perf == "both":
            return "both"
        if letters and perf in ("a", "b"):
            return perf
        pr = prons[1 if perf == "b" else 0] if len(prons) > (1 if perf == "b" else 0) else "he"
        return {"he": "male", "she": "female"}.get(pr, "lead")
    style_perf = {j["styleId"]: j.get("performer", "a") for j in plan.get("jobs", [])}
    for r in rows:
        r["fits"] = []
        # The face the clip shows: from its record (performer) first, else from the
        # style if the current plan still has it, else unknown — and unknown is never
        # "usable": a take with no face on record cannot be placed on a singing window.
        if r.get("performer"):
            r_face = face_of(r["performer"])
        elif r.get("styleId") in style_perf:
            r_face = face_of(style_perf[r["styleId"]])
        else:
            r_face = None
        for j in plan.get("jobs", []):
            if not j.get("voiceRef"):
                continue
            trim = float(j.get("trimStartSec") or 0.0)
            tail = float(j.get("tailSec") or 0.0)
            render = float(j["seconds"])
            covered = render - trim - tail
            if r["seconds"] + 0.05 < covered:
                continue
            face = face_of(j.get("performer", "a"))
            spans = brief.get(j["id"], {}).get("spans", [])
            mine = [(sp["start"], sp["end"]) for sp in spans
                    if not sp.get("partialHead") and not sp.get("partialTail")
                    and (face == "both" or sp.get("who") in ("both", "duet", "lead", face))]
            if not mine:
                continue
            # TWO ALIGNMENTS. A clip as long as the RENDER sits at startSec (it carries
            # the slack); a clip the length of the WINDOW sits at startSec + trim. A 10 s
            # take of him on 21-31 at 0.93 was skipped outright when the window grew its
            # 1 s slack either side (2026-08-23) — the take still covers the window.
            best = None
            for align, base_clip in (("render", 0.0), ("window", -trim)):
                if align == "render" and r["seconds"] + 0.05 < render:
                    continue
                spans_here = [(a, b) for a, b in mine if a + base_clip >= -1e-6 and b + base_clip <= r["seconds"] + 0.05]
                if not spans_here:
                    continue
                try:
                    def env(path, base):
                        out = []
                        for a, b in spans_here:
                            out.extend(envelope(path, base + a, b - a))
                        return out
                    corr, off = best_offset(env(song, float(j["startSec"])), env(r["clip"], base_clip))
                except Exception:   # noqa: BLE001
                    continue
                if best is None or corr > best[0]:
                    best = (float(corr), int(off), align)
            if best is None:
                continue
            corr, off, align = best
            r["fits"].append({"window": j["id"], "styleId": j["styleId"], "corr": round(corr, 2),
                              "offsetMs": off, "align": align,
                              "faceOk": (None if r_face is None else r_face == face),
                              "usable": bool(corr >= 0.6 and abs(off) <= 350 and r_face == face)})
        r["fits"].sort(key=lambda f: -f["corr"])


def collect(project: str, slug: str, sources: list[str], excludes: list[str]) -> list[dict]:
    pairs = []
    for s in sources:
        # ORIGIN is optional and comes after the LAST colon, so absolute paths work.
        if ":" in s and not os.path.exists(s):
            path, _, origin = s.rpartition(":")
        else:
            path, origin = s, ""
        pairs.append((path if os.path.isabs(path) else os.path.join(project, path),
                      origin))
    ex = excludes + [f"{slug}*.mp4"]
    final_videos = os.path.realpath(os.path.join(project, "final/videos"))
    seen_paths, out = set(), []
    for pattern, origin in pairs:
        for base in sorted(glob.glob(pattern)):
            files = ([base] if os.path.isfile(base)
                     else sorted(glob.glob(os.path.join(base, "**/*.mp4"), recursive=True)))
            for f in files:
                if not f.endswith(".mp4"):
                    continue
                real = os.path.realpath(f)
                if real in seen_paths:
                    continue
                # never offer a deliverable as a candidate for a window inside itself
                if os.path.dirname(real) == final_videos:
                    continue
                name = os.path.basename(f)
                if any(glob.fnmatch.fnmatch(name, p) or glob.fnmatch.fnmatch(f, p)
                       for p in ex):
                    continue
                seen_paths.add(real)
                label = origin or os.path.basename(os.path.dirname(base) or base)
                # A PARKED CLIP IS A REJECTED CLIP, wherever it was parked. The roots
                # name the queue's superseded/ explicitly ("parked"), but a recursive
                # root like build/broll* also sweeps ITS superseded/ and those kept the
                # plain "broll" label — so the cutaway pool filled itself with five
                # rejects (Baby Nimbooda, 2026-09-05: last night's empty plates and the
                # off-style pair, while the three good re-renders sat out). The index
                # still lists them (nothing is wasted); the label is what says they may
                # not be picked automatically.
                if f"{os.sep}superseded{os.sep}" in real and "parked" not in label:
                    label = f"{label}-parked"
                out.append({"clip": real, "origin": label})
    return out


def _wid(w) -> str:
    """provenance.json stores the window as an int (4), a live-job record as its id
    ("w04"). The gallery formatted `:02d` and died on the string — caught by the
    synthetic dry-run, not by a render (2026-08-22)."""
    return f"w{int(w):02d}" if isinstance(w, int) or (isinstance(w, str) and w.isdigit()) else str(w)


def _fits_html(r: dict) -> str:
    """'fits w05 (0.73 @ +50 ms)' per clip — reuse is a click, not a memory. Only
    present when the index was built with --plan/--brief/--song."""
    if "fits" not in r:
        return ""
    good = [f for f in r["fits"] if f.get("usable")]
    near = [f for f in r["fits"] if not f.get("usable") and f["corr"] >= 0.6]
    if good:
        return "<br><b style='color:#8fe0a6'>fits " + ", ".join(
            f"{f['window']} ({f['corr']:.2f} @ {f['offsetMs']:+d} ms)" for f in good[:3]) + "</b>"
    if near:
        f = near[0]
        face = {True: "", False: " — wrong face", None: " — face unknown"}[f.get("faceOk")]
        return f"<br>nearest {f['window']} ({f['corr']:.2f} @ {f['offsetMs']:+d} ms{face})"
    return "<br>fits no current window"


def gallery(path: str, rows: list[dict], slug: str) -> None:
    """Generated from the index, never hand-written, with ?v=<mtime> on every asset —
    a hand-written page goes stale the moment the index is rebuilt, and a cached
    thumbnail is indistinguishable from 'nothing changed'."""
    cards = "".join(
        f'<figure><img loading="lazy" src="{html.escape(r["strip"])}?v={int(r["mtime"])}">'
        f'<figcaption><b>{r["id"]}</b> {r["seconds"]:.1f}s · {html.escape(r["origin"])}'
        + (f' · {_wid(r["window"])}' if r.get("window") is not None else "")
        + (" · voice-ref" if r.get("voiceRef") else "")
        + ("" if r.get("hasAudio") else " · <em>no audio</em>")
        + _fits_html(r)
        + "</figcaption></figure>"
        for r in rows if r.get("strip") and os.path.isfile(r["strip"]))
    open(path, "w", encoding="utf-8").write(shell(
        f"{html.escape(slug)} — {len(rows)} candidate clips",
        "Every clip this project owns, one frame a second, with the window it fits and how well — "
        "the cut draws from here before anything renders.",
        f'<div class="g">{cards}</div>', slug=slug,
        extra_css=".g{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:14px}"
                  "figure{margin:0;background:var(--panel);border:1px solid var(--line);border-radius:10px;overflow:hidden}"
                  "img{width:100%;display:block;border:0;border-radius:0}figcaption{padding:8px 10px;font-size:12px;color:var(--ink2)}"
                  "figcaption b{color:var(--ink)}em{color:var(--accent);font-style:normal}"))
    inject_nav(path)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", required=True)
    ap.add_argument("--slug", required=True)
    ap.add_argument("--plan", default="", help="plan.json: compute each clip's FIT per window")
    ap.add_argument("--brief", default="", help="vocal-brief.json: the own-spans judge per window")
    ap.add_argument("--song", default="", help="hook.wav (the master) for the fit correlation")
    ap.add_argument("--source", action="append", default=[],
                    help="PATH_OR_GLOB[:ORIGIN], repeatable; missing paths are skipped")
    ap.add_argument("--exclude-glob", action="append", default=[])
    ap.add_argument("--aspect", default="9:16")
    ap.add_argument("--min-seconds", type=float, default=3.0)
    # 12 is a FALLBACK, not a rule: it is right for 8s windows and wrong for anything
    # longer, where it rejects the film's own clips and returns an empty library.
    # The runner derives it from SCENE_SECONDS; pass it whenever windows are not ~8s.
    ap.add_argument("--max-seconds", type=float, default=12.0,
                    help="a clip longer than a WINDOW is not a candidate for one — this "
                    "is what stops another film's renders being scored at all. Derive it "
                    "from the window length; the 12s default only suits ~8s windows")
    ap.add_argument("--out"), ap.add_argument("--ids"), ap.add_argument("--strips-dir")
    ap.add_argument("--gallery")
    ap.add_argument("--workers", type=int, default=8)
    # A CAP, not a count: the strip samples one frame a second, so an 8s clip gets
    # 8 tiles. The cap only stops a long clip producing an absurdly wide image.
    ap.add_argument("--strip-frames", type=int, default=16, dest="strip_frames",
                    help="maximum tiles per strip (one per second, capped here)")
    ap.add_argument("--strip-width", type=int, default=230)
    ap.add_argument("--no-strips", action="store_true")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    P = os.path.abspath(args.project)
    if not os.path.isdir(P):
        die(f"no such project dir: {P}")
    out_path = args.out or f"{P}/build/library-index.json"
    ids_path = args.ids or f"{P}/build/library-ids.json"
    strips_dir = args.strips_dir or f"{P}/build/strips"
    target = ASPECTS.get(args.aspect)
    if target is None:
        die(f"unknown --aspect {args.aspect!r}; known: {', '.join(ASPECTS)}")
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    os.makedirs(strips_dir, exist_ok=True)

    sources = args.source or [f"{p}:{o}" for p, o in DEFAULT_SOURCES]
    found = collect(P, args.slug, sources, args.exclude_glob + DEFAULT_EXCLUDES)
    if not found:
        die("no clips found — pass --source, or check the project has rendered anything")

    with ThreadPoolExecutor(max_workers=args.workers) as ex:
        probed = list(ex.map(probe, found))
    unprobeable = sum(1 for r in probed if r is None)
    rows = [r for r in probed if r]

    # Dedup keeps the FIRST occurrence in SOURCE order, and `collect()` walks the
    # sources in descending trust — so an operator's pick wins over the same bytes
    # sitting in a bulk account download, and keeps its origin and provenance with it.
    # Sorting by path here instead (as the one-off did) silently hands every duplicate
    # to whichever directory happens to sort first.
    order = {r["clip"]: i for i, r in enumerate(found)}
    seen, uniq, dupes = {}, [], 0
    for r in sorted(rows, key=lambda x: order.get(x["clip"], 1 << 30)):
        key = (r["hash"], r["bytes"], r["seconds"])
        if key in seen:
            dupes += 1
            continue
        seen[key] = r
        uniq.append(r)

    # Persistent ids. Minted for new hashes only, never reassigned, so an authored
    # cut file survives a re-index.
    ledger = {}
    if os.path.isfile(ids_path):
        try:
            ledger = json.load(open(ids_path, encoding="utf-8"))
        except Exception:
            die(f"{ids_path} is unreadable — fix or delete it; deleting invalidates "
                f"every clipId in any authored cut file")
    nxt = 1 + max([int(v[1:]) for v in ledger.values() if v[1:].isdigit()] or [-1])
    prov = load_provenance(P)
    short = overlong = 0
    for r in uniq:
        if r["hash"] not in ledger:
            ledger[r["hash"]] = f"c{nxt:03d}"
            nxt += 1
        r["id"] = ledger[r["hash"]]
        # Computed against the FILM's aspect, not hardcoded to portrait: `h > w` would
        # mark every candidate unusable on a 16:9 pack.
        r["aspectOk"] = abs((r["w"] / r["h"]) - target) <= 0.02
        m = prov.get(r["clip"], {})
        for k in ("window", "styleId", "voiceRef", "performer", "startSec"):
            if k in m:
                r[k] = m[k]
        # A CEILING as well as a floor. --min-seconds only ever refused clips too
        # short to cover a window; nothing refused one that is far too long, and a
        # 20s 1280x720 clip from a DIFFERENT film scored its way into three windows
        # of Great Indian Summer on audio correlation alone. A window is at most
        # --max-seconds long, so anything past it is not a candidate for one —
        # whatever it correlates with.
        r["durationOk"] = (args.min_seconds <= r["seconds"] <= args.max_seconds)
        if r["aspectOk"] and r["seconds"] < args.min_seconds:
            short += 1
        elif r["aspectOk"] and r["seconds"] > args.max_seconds:
            overlong += 1
    json.dump(ledger, open(ids_path, "w"), indent=2)

    cands = [r for r in uniq if r["aspectOk"] and r["durationOk"]]
    if not args.no_strips:
        with ThreadPoolExecutor(max_workers=6) as ex:
            list(ex.map(lambda r: strip(r, strips_dir, args.strip_frames,
                                        args.strip_width), cands))

    by_origin = {}
    for r in cands:
        by_origin[r["origin"]] = by_origin.get(r["origin"], 0) + 1
    doc = {
        "schemaVersion": 1, "project": P, "slug": args.slug, "aspect": args.aspect,
        "generatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "clips": uniq,
        "summary": {
            "found": len(found), "unique": len(uniq), "duplicates": dupes,
            "candidates": len(cands), "byOrigin": by_origin,
            "strips": 0 if args.no_strips else len(cands),
            "rejected": {"aspect": len(uniq) - len(cands) - short - overlong,
                         "short": short, "overlong": overlong,
                         "unprobeable": unprobeable},
        },
    }
    if args.plan and args.brief and args.song and all(os.path.isfile(x) for x in (args.plan, args.brief, args.song)):
        fit_table(uniq, args.plan, args.brief, args.song)
    json.dump(doc, open(out_path, "w"), indent=2)
    if args.gallery:
        gallery(args.gallery, cands, args.slug)

    if args.json:
        print(json.dumps(doc["summary"], indent=2))
    else:
        s = doc["summary"]
        print(f"index_library: {out_path}")
        print(f"  {s['found']} found -> {s['unique']} unique ({s['duplicates']} dupes)"
              f" -> {s['candidates']} candidates at {args.aspect}")
        print(f"  rejected: {s['rejected']['aspect']} wrong aspect, "
              f"{s['rejected']['short']} under {args.min_seconds}s, "
              f"{s['rejected']['overlong']} over {args.max_seconds}s, "
              f"{s['rejected']['unprobeable']} unprobeable")
        print(f"  by origin: {by_origin}")
        if args.gallery:
            print(f"  gallery: {args.gallery}")


if __name__ == "__main__":
    main()
