import json, os, shutil, sys
PUB="/srv/apps/brentwood/laravel/storage/app/public"
STAGE="/srv/apps/brentwooddev/wp-content/themes/kadence-child/_imp_heroes"
os.makedirs(STAGE, exist_ok=True)
manifest=json.load(open('/tmp/page-heroes-manifest.json'))
only=set(sys.argv[1:]) if len(sys.argv)>1 else None   # subset of slugs, else all
TYPEMAP={'image':'image','slider':'carousel','dual':'dual','video':'video'}
out=[]
for r in manifest:
    if only and r['slug'] not in only: continue
    if r['detected'] not in TYPEMAP: continue
    if not r['media']: continue
    files=[]
    for rel in r['media']:
        src=PUB+'/'+rel.lstrip('/')
        if not os.path.isfile(src): continue
        flat=rel.lstrip('/').replace('/','-')
        dst=STAGE+'/'+flat
        if not os.path.exists(dst): shutil.copy2(src,dst)
        files.append(flat)
    if files:
        out.append({"slug":r['slug'],"hero_type":TYPEMAP[r['detected']],
                    "source_rel":r['media'],"files":files})
json.dump(out, open(STAGE+'/import.json','w'), indent=1)
# fix perms so container (www-data) can read
for f in os.listdir(STAGE):
    try: os.chmod(STAGE+'/'+f, 0o664)
    except: pass
print(f"staged {len(out)} pages, {sum(len(x['files']) for x in out)} files into {STAGE}")
