#!/usr/bin/env python3
"""Measure and repair the subtitles of copies this addon already fetched.
New ingests sync their sidecars as they land (_fetch_subtitles_for). This is
the one-off for everything fetched before that existed. It calls the same
_sync_subtitles the ingest uses, which skips any track already recorded, so a
re-run -- or an interrupted run resumed -- costs one stat per track.
Scope is the ingest queue (_fetched_dests), the same scope as Delete: copies
this addon fetched.
Usage:
nice -n 15 .venv/bin/python3 sync_subtitles.py [--limit N] [PATH ...]
"""
import argparse
import os
import sys
import time
import addon
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("paths", nargs="*", help="specific library copies (default: all fetched)")
ap.add_argument("--limit", type=int, default=0)
args = ap.parse_args()
if not addon._subsync_available():
print(f"ffsubsync not found at {addon.SUBSYNC_BIN}", file=sys.stderr)
return 1
copies = args.paths or sorted(p for p in addon._fetched_dests() if os.path.exists(p))
if args.limit:
copies = copies[:args.limit]
total = {"tracks": 0, "in_sync": 0, "corrected": 0, "unfixable": 0, "unmeasured": 0}
for i, dest in enumerate(copies, 1):
t0 = time.time()
r = addon._sync_subtitles(dest)
for k in total:
total[k] += r[k]
print(f"[{i}/{len(copies)}] {os.path.basename(dest)}: {r} "
f"({time.time() - t0:.0f}s)", flush=True)
print("total:", total, flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())