"""Stage local 'Only Images' crops that match prod question_image paths.

Reads _needimg.txt (prod paths like p6/images/<slug>-q<n>.png), matches each by
basename to a file in 'Only Images/', and copies it into _cropstage/<path> so the
tar preserves the exact prod path. Upload target = storage/app/public/.
"""
import os, shutil
base = os.path.dirname(os.path.abspath(__file__))
oi = os.path.join(base, "Only Images")
stage = os.path.join(base, "_cropstage")
if os.path.exists(stage):
    shutil.rmtree(stage)
paths = [l.strip() for l in open(os.path.join(base, "_needimg.txt"), encoding="utf-8") if l.strip()]
have = set(os.listdir(oi)) if os.path.isdir(oi) else set()
m = 0; miss = 0; bylevel = {}
for p in paths:
    b = os.path.basename(p)
    if b in have:
        dst = os.path.join(stage, p.replace("/", os.sep))
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        shutil.copy(os.path.join(oi, b), dst)
        m += 1
        lvl = p.split("/")[0]
        bylevel[lvl] = bylevel.get(lvl, 0) + 1
    else:
        miss += 1
print("matched=%d  missing(local crop not ready)=%d" % (m, miss))
print("by level:", bylevel)
