#!/usr/bin/env python3
"""In-container patch: add scopeKey + revisionId to the served OTA manifest.

The Android expo-manifests SDK requires:
  ExpoUpdatesManifest.getScopeKey()  -> extra.scopeKey  (must be present)
  Manifest.getRevisionId()            -> expoClient.revisionId (must be present)
Both are currently MISSING from the served manifest => UpdateFailedToLoad at
UpdateFactory.kt:19. This patch adds them. Reversibility: a .bak of the
original file is taken before editing (already exists from a prior cp), and
this writes a fresh timestamped .bak too.
"""
import shutil
import time

SRC = "/home/bun/server/src/modules/expo/manifest.ts"
BAK = f"{SRC}.bak-scopekey-{time.strftime('%Y%m%d_%H%M%S')}"

with open(SRC) as f:
    src = f.read()

# Safety: only proceed if the target block is present and not already fixed.
block_old = """      extra: {
        expoClient: update.appJson,
      },"""
block_new = """      extra: {
        expoClient: { ...(update.appJson || {}), revisionId: update.updateId },
        scopeKey: (update.appJson && update.appJson.slug) || 'pixiesprout',
      },"""

if block_old not in src:
    print("ERROR: target extra{} block not found (already patched or structure changed).")
    raise SystemExit(1)
if "revisionId: update.updateId" in src:
    print("ALREADY_PATCHED: revisionId/scopeKey present; no change.")
    raise SystemExit(0)

# Backup
shutil.copy2(SRC, BAK)
print("Backup:", BAK)

# Apply
src = src.replace(block_old, block_new, 1)
with open(SRC, "w") as f:
    f.write(src)
print("PATCHED_manifest.ts")
