import subprocess, os, sys

PROJ = "/root/sgt_code_workspace/PixieSprout"
os.chdir(PROJ)
env = os.environ.copy()
env["HOME"] = "/root"
env["ANDROID_HOME"] = "/opt/android-sdk"
env["NODE_ENV"] = "production"

# Decrypt keystore password (same as build-and-sign.sh)
gpg_pass = open("/opt/secure/keystores/pixiesprout/gpg-passphrase.env").read().strip().split("=", 1)[1]
res = subprocess.run(
    ["gpg", "--quiet", "--batch", "--passphrase-fd", "0", "--decrypt",
     "/opt/secure/keystores/pixiesprout/keystore.properties.gpg"],
    input=gpg_pass.encode(), capture_output=True)
store_pass = ""
for line in res.stdout.decode().strip().split("\n"):
    if line.startswith("storePassword="):
        store_pass = line.split("=", 1)[1]
        break
env["PIXIESPROUT_STORE_PASS"] = store_pass
print("keystore pass loaded:", bool(store_pass))

# Embed fresh bundle
os.makedirs("android/app/src/main/assets", exist_ok=True)
import shutil
hbc = os.path.join(PROJ, "dist/_expo/static/js/android/index-ca00db40d697ac3283fc011efcbca5a6.hbc")
shutil.copy2(hbc, "android/app/src/main/assets/index.android.bundle")
print("bundle embedded")

# assembleRelease WITHOUT clean (the skill warns clean breaks dex merge on this project)
print("starting assembleRelease...")
r = subprocess.run(["bash", "gradlew", "assembleRelease"], cwd="android", env=env,
                   timeout=1200, capture_output=True, text=True)
print("exit:", r.returncode)
# print last 40 lines
tail = (r.stdout or "")[-4000:]
print(tail[-4000:])
if r.returncode != 0:
    print("STDERR tail:", (r.stderr or "")[-2000:])
