#!/usr/bin/env python3
"""
Backfill *-CENTER-ims.corr-xml files from the corresponding physical scene IMS files.

For each <models_dir>/<ts>-CENTER/ directory that is missing its IMS file, copy
<models_dir>/<ts>/<ts>-ims.corr-xml  →  <models_dir>/<ts>-CENTER/<ts>-CENTER-ims.corr-xml

The content is copied as-is (camera LLA from the reference scene is close enough
for testing; createCenterClt() will overwrite with a proper averaged value on the
next full run).

Usage:
    python3 backfill_center_ims.py [<models_root>...]

    Defaults to /home/elphel/lwir16-proc/LV/models if no arguments are given.
"""

import sys
import os
import shutil
import glob

IMS_SUFFIX = "-ims.corr-xml"

def backfill(models_root):
    center_dirs = sorted(glob.glob(os.path.join(models_root, "*-CENTER")))
    if not center_dirs:
        print(f"  No *-CENTER directories found under {models_root}")
        return 0, 0

    copied = skipped = 0
    for center_dir in center_dirs:
        center_name = os.path.basename(center_dir)          # e.g. 1773135527_803834-CENTER
        ts = center_name.replace("-CENTER", "")              # e.g. 1773135527_803834

        src = os.path.join(models_root, ts, ts + IMS_SUFFIX)
        dst = os.path.join(center_dir, center_name + IMS_SUFFIX)

        if os.path.exists(dst):
            print(f"  SKIP  {dst}  (already exists)")
            skipped += 1
            continue
        if not os.path.exists(src):
            print(f"  MISS  {src}  (source not found, skipping)")
            skipped += 1
            continue

        shutil.copy2(src, dst)
        print(f"  COPY  {src}")
        print(f"     -> {dst}")
        copied += 1

    return copied, skipped


def main():
    roots = sys.argv[1:] if len(sys.argv) > 1 else \
            sorted(glob.glob("/home/elphel/lwir16-proc/LV/models/models_*"))

    total_copied = total_skipped = 0
    for root in roots:
        print(f"\n{root}")
        c, s = backfill(root)
        total_copied  += c
        total_skipped += s

    print(f"\nDone: {total_copied} copied, {total_skipped} skipped.")


if __name__ == "__main__":
    main()
