#!/usr/bin/env python3
"""check_track_caches.py SRC ARM_DIR: for every tracks/*.dbm of an assembled arm, run the frozen loader's own
signature test (tracks._tracks_db_signature vs the packed store's and the crossing cache's recorded signature).
Exit 0 = every cache would be used, as in the original fits."""
import glob, json, os, sys
sys.path.insert(0, os.path.join(sys.argv[1], 'spiral-fitting'))
import numpy as np, tracks
bad = 0
dbms = sorted(glob.glob(os.path.join(sys.argv[2], 'tracks', '*.dbm')))
if not dbms:
    sys.exit(f'no tracks/*.dbm under {sys.argv[2]}: nothing checked')
for dbm in dbms:
    sig = [list(x) for x in tracks._tracks_db_signature(dbm)]
    store = tracks.track_store_path(dbm); cache = tracks.track_crossing_cache_path(dbm)
    for kind, rec in (('packed store', json.load(open(store / 'metadata.json')).get('source_db_signature') if store.is_dir() else None),
                      ('crossing cache', json.loads(str(np.load(cache, allow_pickle=False)['metadata'].item())).get('db_signature') if cache.is_file() else None)):
        ok = rec is not None and tracks._db_signatures_match(rec, sig)
        bad += not ok
        print(f"{'OK  ' if ok else 'FAIL'} {os.path.basename(dbm)} {kind}: {'absent' if rec is None else 'signature ' + ('matches' if ok else f'{rec} != {sig}')}")
sys.exit(1 if bad else 0)
