#!/usr/bin/env python3
"""Fix Windows backslash paths in metadata.json + create OTA upload zip.

Replicates the server-side fix_and_zip_ota.py exactly so the expo-ota server
accepts the upload (it requires metadata.json + app.json + package.json at the
zip root, and metadata asset paths must use forward slashes).

Run from the PixieSprout project root after `npx expo export --platform android`.
Creates pixiesprout-ota.zip ready for upload.

Usage:
    python fix_and_zip_ota.py [project_root]
"""
import zipfile, json, os, sys

project = sys.argv[1] if len(sys.argv) > 1 else "."
dist = os.path.join(project, "dist")
meta_path = os.path.join(dist, "metadata.json")

with open(meta_path, "r") as f:
    meta = json.load(f)

bs, sl = chr(92), chr(47)  # backslash, forward slash

for asset in meta.get("fileMetadata", {}).get("android", {}).get("assets", []):
    asset["path"] = asset["path"].replace(bs, sl)

bundle = meta.get("fileMetadata", {}).get("android", {}).get("bundle", "")
if bs in bundle:
    meta["fileMetadata"]["android"]["bundle"] = bundle.replace(bs, sl)

fixed_path = os.path.join(dist, "metadata_fixed.json")
with open(fixed_path, "w") as f:
    json.dump(meta, f, separators=(",", ":"))

zip_path = os.path.join(project, "pixiesprout-ota.zip")
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
    zf.write(fixed_path, "metadata.json")
    for name in ("app.json", "package.json"):
        src = os.path.join(project, name)
        if os.path.exists(src):
            zf.write(src, name)
    for root, dirs, files in os.walk(dist):
        for f in files:
            if f in ("metadata.json", "metadata_fixed.json"):
                continue
            fp = os.path.join(root, f)
            zf.write(fp, os.path.relpath(fp, dist))

size_mb = os.path.getsize(zip_path) / (1024 * 1024)
print(f"Created {zip_path} ({size_mb:.1f} MB)")
