import json, os, shutil, zipfile, subprocess, sys

SRC = "/opt/expo-ota/updates/pixiesprout/1.0.112/6a76f82ebce64410088d0759"
WORK = "/tmp/ota111"
ZIP = "/tmp/pixiesprout-ota-1.0.111.zip"

# 1. Fresh working dir (reversible: pure copy, original untouched)
if os.path.exists(WORK):
    shutil.rmtree(WORK)
os.makedirs(WORK)

# 2. Copy the existing good upload content (bundle + assets + metadata + package)
for item in os.listdir(SRC):
    s = os.path.join(SRC, item)
    d = os.path.join(WORK, item)
    if os.path.isdir(s):
        shutil.copytree(s, d)
    else:
        shutil.copy2(s, d)

# 3. Fix app.json version -> 1.0.111 (keep manifest consistent; runtimeVersion is echoed from request param anyway)
ap = os.path.join(WORK, "app.json")
with open(ap) as f:
    app = json.load(f)
app["expo"]["version"] = "1.0.111"
with open(ap, "w") as f:
    json.dump(app, f, indent=2)

# 4. Confirm metadata.json bundle path + forward slashes
with open(os.path.join(WORK, "metadata.json")) as f:
    meta = json.load(f)
bundle = meta["fileMetadata"]["android"]["bundle"]
assert os.path.exists(os.path.join(WORK, bundle)), f"bundle missing: {bundle}"
print("bundle:", bundle, "OK")
print("app.json version now:", app["expo"]["version"])

# 5. Zip (root: metadata.json, app.json, package.json, _expo/, assets/)
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED) as zf:
    for root, dirs, files in os.walk(WORK):
        for fn in files:
            full = os.path.join(root, fn)
            rel = os.path.relpath(full, WORK)
            zf.write(full, rel)
print("zip written:", ZIP, os.path.getsize(ZIP), "bytes")
print("entries:", len(zipfile.ZipFile(ZIP).namelist()))
