File size: 23,678 Bytes
3967721
580f513
3967721
 
 
 
 
 
580f513
3967721
 
 
 
580f513
3967721
 
 
 
 
580f513
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
 
 
 
 
3967721
580f513
3967721
 
580f513
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
3967721
 
 
580f513
3967721
 
 
 
 
580f513
 
3967721
 
 
 
 
 
9455ad5
3967721
580f513
3967721
 
 
 
 
580f513
 
 
 
 
 
3967721
580f513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3967721
 
 
 
 
 
 
 
 
 
580f513
 
 
 
 
 
 
 
 
 
 
 
3967721
 
580f513
3967721
 
 
 
580f513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3967721
 
580f513
 
 
 
3967721
580f513
 
 
 
 
 
 
 
 
 
 
 
3967721
580f513
 
 
 
 
 
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3967721
 
 
 
 
 
 
580f513
 
 
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
 
 
 
 
 
 
 
 
 
3967721
 
580f513
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
 
 
3967721
580f513
 
 
 
 
3967721
580f513
 
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
580f513
 
 
 
 
 
3967721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
#!/usr/bin/env python3
"""Validate active indexes and optional Viewer/repository snapshots."""

from __future__ import annotations

import argparse
import csv
import json
import math
import re
import statistics
import sys
from collections import Counter
from datetime import date
from pathlib import Path
from urllib.parse import unquote, urlparse


RECORD_ID_RE = re.compile(r"^tla-[0-9a-f]{16}$")
HASH_RE = re.compile(r"^[0-9a-f]{64}$")
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
TIME_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
DIMENSIONS_RE = re.compile(r"^\d+(?:\.\d+)?x\d+(?:\.\d+)?$")
DIRECT_STANDARD_RE = re.compile(r"^Standard_Time_Lapses/[^/]+\.mp4$")
DIRECT_PRE_STANDARD_RE = re.compile(r"^Pre_Standard_Time_Lapses/[^/]+\.mp4$")

REQUIRED_FIELDS = [
    "file_name",
    "record_id",
    "collection_tier",
    "is_canonical",
    "acquisition_protocol_version",
    "date",
    "time",
    "tool",
    "medium",
    "support",
    "dimensions",
    "duration_seconds",
    "width_px",
    "height_px",
    "orientation",
    "encoded_frame_rate",
    "video_codec",
    "pixel_format",
    "container",
    "has_audio",
    "hub_xet_hash",
    "original_filename",
    "provenance_status",
    "legacy_provenance_path",
    "legacy_related_references",
    "evidence_method",
    "provenance_reference_duration_delta_seconds",
    "size_bytes",
    "notes",
]

PRE_STANDARD_REQUIRED_FIELDS = REQUIRED_FIELDS


def viewer_path(row: dict[str, object]) -> str:
    video = row.get("video")
    if not isinstance(video, dict) or not isinstance(video.get("src"), str):
        return ""
    path = unquote(urlparse(video["src"]).path)
    marker = "/resolve/"
    if marker not in path:
        return ""
    after_revision = path.split(marker, 1)[1]
    parts = after_revision.split("/", 1)
    return parts[1] if len(parts) == 2 else ""


def load_csv(path: Path) -> tuple[list[str], list[dict[str, str]]]:
    with path.open("r", encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle)
        if reader.fieldnames is None:
            raise ValueError("metadata file has no header")
        return list(reader.fieldnames), list(reader)


def valid_calendar_date(value: str) -> bool:
    if not DATE_RE.fullmatch(value):
        return False
    try:
        date.fromisoformat(value)
    except ValueError:
        return False
    return True


def validate_multi_value(
    row: dict[str, str], label: str, field: str, errors: list[str]
) -> None:
    value = row.get(field, "")
    if "|" in value:
        errors.append(f"{label}: {field} still uses a pipe separator")
    items = [item.strip() for item in value.split(";") if item.strip()]
    if value and len(items) != len(value.split(";")):
        errors.append(f"{label}: {field} contains an empty list item")
    if len(items) != len(set(items)):
        errors.append(f"{label}: {field} contains duplicate list values")


def validate_positive_number(
    row: dict[str, str],
    label: str,
    field: str,
    errors: list[str],
    *,
    integer: bool = False,
) -> float | None:
    value = row.get(field, "")
    if not value:
        errors.append(f"{label}: technical field {field} is blank")
        return None
    try:
        parsed = float(value)
    except ValueError:
        errors.append(f"{label}: technical field {field} is not numeric")
        return None
    if not math.isfinite(parsed) or parsed <= 0:
        errors.append(f"{label}: technical field {field} must be positive")
        return None
    if integer and not parsed.is_integer():
        errors.append(f"{label}: technical field {field} must be an integer")
        return None
    return parsed


def validate_technical_row(
    row: dict[str, str], label: str, errors: list[str]
) -> None:
    duration = validate_positive_number(row, label, "duration_seconds", errors)
    width = validate_positive_number(row, label, "width_px", errors, integer=True)
    height = validate_positive_number(row, label, "height_px", errors, integer=True)
    frame_rate = validate_positive_number(row, label, "encoded_frame_rate", errors)
    size = validate_positive_number(row, label, "size_bytes", errors, integer=True)
    del duration, frame_rate, size

    for field in ("orientation", "video_codec", "pixel_format", "container"):
        if not row.get(field, ""):
            errors.append(f"{label}: technical field {field} is blank")
    if row.get("has_audio", "").lower() not in {"true", "false"}:
        errors.append(f"{label}: has_audio must be true or false")
    if not HASH_RE.fullmatch(row.get("hub_xet_hash", "")):
        errors.append(f"{label}: hub_xet_hash must be 64 lowercase hexadecimal characters")

    if width is not None and height is not None:
        expected_orientation = (
            "portrait" if height > width else "landscape" if width > height else "square"
        )
        if row.get("orientation") != expected_orientation:
            errors.append(
                f"{label}: orientation {row.get('orientation')!r} conflicts with "
                f"{int(width)}x{int(height)}"
            )


def validate(
    metadata_csv: Path,
    viewer_json: Path | None,
    pre_standard_metadata: Path | None,
    repo_files_json: Path | None,
) -> dict[str, object]:
    fields, rows = load_csv(metadata_csv)
    errors: list[str] = []
    warnings: list[str] = []
    pre_standard_rows: list[dict[str, str]] = []
    repo_counts: dict[str, int] = {}
    repo_unindexed_standard: list[str] = []
    repo_unindexed_pre_standard: list[str] = []

    missing_fields = [field for field in REQUIRED_FIELDS if field not in fields]
    if missing_fields:
        errors.append(f"missing required columns: {missing_fields}")

    def duplicate_values(records: list[dict[str, str]], field: str) -> list[str]:
        values = [row.get(field, "") for row in records if row.get(field, "")]
        return sorted(value for value, count in Counter(values).items() if count > 1)

    for field in ("file_name", "record_id", "hub_xet_hash"):
        duplicates = duplicate_values(rows, field)
        if duplicates:
            errors.append(f"duplicate {field} values: {duplicates[:5]}")

    for index, row in enumerate(rows, start=2):
        label = row.get("file_name") or f"CSV row {index}"
        if not DIRECT_STANDARD_RE.fullmatch(row.get("file_name", "")):
            errors.append(f"{label}: canonical path must be a direct Standard_Time_Lapses MP4")
        if not RECORD_ID_RE.fullmatch(row.get("record_id", "")):
            errors.append(f"{label}: invalid record_id")
        if row.get("collection_tier") != "standard":
            errors.append(f"{label}: collection_tier must be standard")
        if row.get("is_canonical", "").lower() != "true":
            errors.append(f"{label}: is_canonical must be true")
        if row.get("acquisition_protocol_version") != "standard-2025-07-13":
            errors.append(f"{label}: unexpected acquisition protocol version")
        if not valid_calendar_date(row.get("date", "")):
            errors.append(f"{label}: invalid or missing finish date")
        if row.get("time") and not TIME_RE.fullmatch(row["time"]):
            errors.append(f"{label}: invalid finish time")
        if not DIMENSIONS_RE.fullmatch(row.get("dimensions", "")):
            errors.append(f"{label}: invalid dimensions")
        if not row.get("tool", ""):
            errors.append(f"{label}: canonical tool is blank")
        if not row.get("medium", ""):
            errors.append(f"{label}: canonical medium is blank")
        if not row.get("support", ""):
            errors.append(f"{label}: canonical support is blank")
        for field in ("tool", "medium"):
            validate_multi_value(row, label, field, errors)

        basename = Path(row.get("file_name", "")).name
        filename_parts = basename.split(".")
        expected_time = row.get("time", "").replace(":", "") or "UnknownTime"
        if len(filename_parts) < 2 or filename_parts[0] != row.get("date"):
            errors.append(f"{label}: filename date differs from metadata date")
        elif filename_parts[1] != expected_time:
            errors.append(f"{label}: filename time differs from metadata time")

        validate_technical_row(row, label, errors)

    standard_30x40_paper = sum(
        row.get("dimensions") == "30x40" and row.get("support") == "Paper"
        for row in rows
    )
    if standard_30x40_paper:
        warnings.append(
            f"{standard_30x40_paper} canonical 30x40 rows use support=Paper while "
            "Archive_Specifications.md describes 30x40 Illustration Board; curator review required"
        )

    if pre_standard_metadata:
        pre_fields, pre_standard_rows = load_csv(pre_standard_metadata)
        missing_pre_fields = [
            field for field in PRE_STANDARD_REQUIRED_FIELDS if field not in pre_fields
        ]
        if missing_pre_fields:
            errors.append(
                f"pre-standard metadata is missing required columns: {missing_pre_fields}"
            )
        for field in ("file_name", "record_id", "hub_xet_hash"):
            duplicates = duplicate_values(pre_standard_rows, field)
            if duplicates:
                errors.append(f"duplicate pre-standard {field} values: {duplicates[:5]}")

        all_rows = rows + pre_standard_rows
        for field in ("record_id", "hub_xet_hash"):
            duplicates = duplicate_values(all_rows, field)
            if duplicates:
                errors.append(f"duplicate cross-tier {field} values: {duplicates[:5]}")

        unknown_date_with_time = 0
        for index, row in enumerate(pre_standard_rows, start=2):
            name = row.get("file_name", "")
            label = name or f"pre-standard CSV row {index}"
            if not name or "/" in name or "\\" in name or not name.endswith(".mp4"):
                errors.append(
                    f"pre-standard CSV row {index}: file_name must be a direct MP4 basename"
                )
            if not RECORD_ID_RE.fullmatch(row.get("record_id", "")):
                errors.append(f"{label}: invalid record_id")
            if row.get("collection_tier") != "pre_standard":
                errors.append(f"{label}: collection_tier must be pre_standard")
            if row.get("is_canonical", "").lower() != "false":
                errors.append(f"{label}: is_canonical must be false")
            if row.get("acquisition_protocol_version"):
                errors.append(f"{label}: pre-standard acquisition protocol must be blank")

            if row.get("date"):
                if not valid_calendar_date(row["date"]):
                    errors.append(f"{label}: invalid finish date")
            elif row.get("time"):
                unknown_date_with_time += 1
            if row.get("time") and not TIME_RE.fullmatch(row["time"]):
                errors.append(f"{label}: invalid finish time")
            if not DIMENSIONS_RE.fullmatch(row.get("dimensions", "")):
                errors.append(f"{label}: invalid dimensions")
            for field in ("tool", "medium"):
                validate_multi_value(row, label, field, errors)
            validate_technical_row(row, label, errors)

        if unknown_date_with_time:
            warnings.append(
                f"{unknown_date_with_time} pre-standard rows retain a time while the date is unknown; "
                "confirm that 00:00 means documented midnight rather than a placeholder"
            )
        missing_material_rows = sum(
            not row.get("tool") or not row.get("medium") or not row.get("support")
            for row in pre_standard_rows
        )
        if missing_material_rows:
            warnings.append(
                f"{missing_material_rows} pre-standard rows retain incomplete material fields"
            )

    if repo_files_json:
        loaded_inventory = json.loads(repo_files_json.read_text(encoding="utf-8"))
        repo_items: dict[str, dict[str, object]] = {}
        if isinstance(loaded_inventory, list) and all(
            isinstance(path, str) for path in loaded_inventory
        ):
            loaded_paths = loaded_inventory
        elif isinstance(loaded_inventory, dict) and isinstance(
            loaded_inventory.get("siblings"), list
        ):
            loaded_paths = []
            for item in loaded_inventory["siblings"]:
                if not isinstance(item, dict) or not isinstance(item.get("rfilename"), str):
                    errors.append("Hub repository inventory contains an invalid sibling entry")
                    continue
                path = item["rfilename"]
                loaded_paths.append(path)
                repo_items[path] = item
        else:
            loaded_paths = []
            errors.append(
                "repository snapshot must be a JSON path list or a Hub API object with siblings"
            )

        if loaded_paths:
            repo_paths = set(loaded_paths)
            standard_files = {path for path in repo_paths if DIRECT_STANDARD_RE.fullmatch(path)}
            pre_standard_files = {
                path for path in repo_paths if DIRECT_PRE_STANDARD_RE.fullmatch(path)
            }
            provenance_files = {
                path
                for path in repo_paths
                if path.startswith("Standard_Time_Lapses/Provenance/")
                and path.endswith(".mp4")
            }
            canonical_paths = {row.get("file_name", "") for row in rows}
            active_pre_paths = {
                f"Pre_Standard_Time_Lapses/{row.get('file_name', '')}"
                for row in pre_standard_rows
                if row.get("file_name")
            }
            missing_canonical_targets = sorted(canonical_paths.difference(repo_paths))
            missing_pre_targets = sorted(active_pre_paths.difference(repo_paths))
            repo_unindexed_standard = sorted(standard_files.difference(canonical_paths))
            repo_unindexed_pre_standard = sorted(
                pre_standard_files.difference(active_pre_paths)
            )
            if missing_canonical_targets:
                errors.append(
                    f"{len(missing_canonical_targets)} canonical metadata paths have no repository file"
                )
            if missing_pre_targets:
                errors.append(
                    f"{len(missing_pre_targets)} active pre-standard metadata paths have no repository file"
                )
            if repo_unindexed_pre_standard:
                errors.append(
                    f"{len(repo_unindexed_pre_standard)} published pre-standard files are absent from the active index"
                )
            if repo_unindexed_standard:
                warnings.append(
                    f"{len(repo_unindexed_standard)} direct standard files are pending metadata ingestion"
                )

            hash_mismatches: list[str] = []
            size_mismatches: list[str] = []
            missing_blob_metadata: list[str] = []
            if repo_items:
                indexed_paths_and_rows = [
                    *((row.get("file_name", ""), row) for row in rows),
                    *(
                        (f"Pre_Standard_Time_Lapses/{row.get('file_name', '')}", row)
                        for row in pre_standard_rows
                    ),
                ]
                for path, row in indexed_paths_and_rows:
                    item = repo_items.get(path, {})
                    lfs = item.get("lfs") if isinstance(item, dict) else None
                    if not isinstance(lfs, dict):
                        missing_blob_metadata.append(path)
                        continue
                    expected_hash = item.get("xetHash")
                    expected_size = item.get("size")
                    if expected_size is None:
                        expected_size = lfs.get("size")
                    if not isinstance(expected_hash, str) or expected_size is None:
                        missing_blob_metadata.append(path)
                        continue
                    if row.get("hub_xet_hash", "").lower() != expected_hash.lower():
                        hash_mismatches.append(path)
                    if row.get("size_bytes", "") != str(expected_size):
                        size_mismatches.append(path)

                if missing_blob_metadata:
                    errors.append(
                        f"{len(missing_blob_metadata)} indexed files lack Hub LFS identity metadata"
                    )
                if hash_mismatches:
                    errors.append(
                        f"{len(hash_mismatches)} indexed hashes differ from the Hub inventory"
                    )
                if size_mismatches:
                    errors.append(
                        f"{len(size_mismatches)} indexed byte sizes differ from the Hub inventory"
                    )

            repo_counts = {
                "repository_files": len(repo_paths),
                "direct_standard_video_files": len(standard_files),
                "direct_pre_standard_video_files": len(pre_standard_files),
                "provenance_video_files": len(provenance_files),
                "missing_canonical_metadata_targets": len(missing_canonical_targets),
                "missing_pre_standard_metadata_targets": len(missing_pre_targets),
                "missing_hub_identity_metadata": len(missing_blob_metadata),
                "content_hash_mismatches": len(hash_mismatches),
                "size_mismatches": len(size_mismatches),
            }

    viewer_rows: list[dict[str, object]] = []
    viewer_counts: dict[str, int] = {}
    if viewer_json:
        loaded = json.loads(viewer_json.read_text(encoding="utf-8"))
        if not isinstance(loaded, list):
            errors.append("Viewer snapshot must be a JSON list")
        else:
            viewer_rows = [row for row in loaded if isinstance(row, dict)]
            paths = [viewer_path(row) for row in viewer_rows]
            tiers = Counter(path.split("/", 1)[0] for path in paths if "/" in path)
            viewer_counts = dict(sorted(tiers.items()))

            canonical_viewer = {
                viewer_path(row): row
                for row in viewer_rows
                if viewer_path(row).startswith("Standard_Time_Lapses/")
            }
            metadata_paths = {row["file_name"] for row in rows}
            missing_from_viewer = sorted(metadata_paths.difference(canonical_viewer))
            missing_from_metadata = sorted(set(canonical_viewer).difference(metadata_paths))
            if missing_from_viewer:
                errors.append(
                    f"{len(missing_from_viewer)} metadata paths are absent from the Viewer snapshot"
                )
            if missing_from_metadata:
                errors.append(
                    f"{len(missing_from_metadata)} canonical Viewer paths are absent from metadata.csv"
                )

            by_path = {row["file_name"]: row for row in rows}
            for path, viewer_row in canonical_viewer.items():
                metadata_row = by_path.get(path)
                if not metadata_row:
                    continue
                for field in (
                    "date",
                    "time",
                    "support",
                    "dimensions",
                    "orientation",
                    "video_codec",
                    "pixel_format",
                    "container",
                    "hub_xet_hash",
                ):
                    left = metadata_row.get(field, "")
                    right_value = viewer_row.get(field)
                    right = "" if right_value is None else str(right_value)
                    if left != right:
                        errors.append(f"{path}: {field} differs from Viewer snapshot")

            pre_standard_viewer_rows = [
                row
                for row in viewer_rows
                if viewer_path(row).startswith("Pre_Standard_Time_Lapses/")
            ]
            pre_standard_without_technical = sum(
                row.get("duration_seconds") is None for row in pre_standard_viewer_rows
            )
            if pre_standard_without_technical:
                warnings.append(
                    f"{pre_standard_without_technical} pre-standard Viewer rows lack duration metadata"
                )

    all_active_rows = rows + pre_standard_rows
    durations = [
        float(row["duration_seconds"])
        for row in all_active_rows
        if row.get("duration_seconds")
    ]
    sizes = [int(row["size_bytes"]) for row in all_active_rows if row.get("size_bytes")]
    orientations = Counter(
        row.get("orientation", "") or "<missing>" for row in all_active_rows
    )
    audio = Counter(row.get("has_audio", "") or "<missing>" for row in all_active_rows)

    if audio.get("True", 0) + audio.get("true", 0) > 0:
        warnings.append("published masters commonly retain audio streams; rights/privacy review is still required")
    warnings.append(
        "encoded_frame_rate is playback rate, not original drawing-time sampling"
    )

    return {
        "ok": not errors,
        "errors": errors,
        "warnings": warnings,
        "statistics": {
            "metadata_rows": len(rows),
            "metadata_columns": len(fields),
            "viewer_rows": len(viewer_rows),
            "viewer_collection_counts": viewer_counts,
            "pre_standard_metadata_rows": len(pre_standard_rows),
            "repository_inventory": repo_counts,
            "unindexed_direct_standard_files": repo_unindexed_standard,
            "unindexed_direct_pre_standard_files": repo_unindexed_pre_standard,
            "active_rows": len(all_active_rows),
            "unique_record_ids": len(
                {row.get("record_id", "") for row in all_active_rows if row.get("record_id")}
            ),
            "unique_nonempty_hashes": len(
                {
                    row.get("hub_xet_hash", "")
                    for row in all_active_rows
                    if row.get("hub_xet_hash")
                }
            ),
            "unknown_finish_dates": sum(not row.get("date") for row in all_active_rows),
            "unknown_finish_times": sum(not row.get("time") for row in all_active_rows),
            "orientation_counts": dict(sorted(orientations.items())),
            "audio_counts": dict(sorted(audio.items())),
            "playback_hours": round(sum(durations) / 3600, 2),
            "median_playback_seconds": round(statistics.median(durations), 3),
            "indexed_size_tb_decimal": round(sum(sizes) / 1_000_000_000_000, 3),
        },
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("metadata_csv", type=Path)
    parser.add_argument("--viewer-json", type=Path)
    parser.add_argument("--pre-standard-metadata", type=Path)
    parser.add_argument(
        "--repo-files-json",
        "--repo-inventory-json",
        dest="repo_files_json",
        type=Path,
    )
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    report = validate(
        args.metadata_csv,
        args.viewer_json,
        args.pre_standard_metadata,
        args.repo_files_json,
    )
    rendered = json.dumps(report, indent=2, sort_keys=True)
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(rendered + "\n", encoding="utf-8")
    print(rendered)
    if not report["ok"]:
        sys.exit(1)


if __name__ == "__main__":
    main()