#!/usr/bin/env python3
"""Starfall Haven signed-APK emulator smoke test.

Runs an ordinary install/upgrade, launches the landscape activity, captures each
runtime boundary, exercises semantic controls with 1212x540 screenshot-space
coordinates, force-stops, and verifies a cold relaunch. Intended for the API-35
Mountaincore emulator after it has booted.
"""
from pathlib import Path
import subprocess, sys, time

APK = Path(sys.argv[1] if len(sys.argv) > 1 else "artifacts/Starfall-Haven-0.1.0-release.apk").resolve()
OUT = Path(sys.argv[2] if len(sys.argv) > 2 else "/tmp/starfall-qa")
PKG = "space.animefu.starfallhaven"
ACT = f"{PKG}/.MainActivity"
OUT.mkdir(parents=True, exist_ok=True)

def run(*args, capture=True):
    return subprocess.run(args, check=True, text=True, stdout=subprocess.PIPE if capture else None, stderr=subprocess.STDOUT).stdout if capture else ""
def adb(*args, capture=True): return run("adb", *args, capture=capture)
def shot(name):
    (OUT / f"{name}.png").write_bytes(subprocess.run(["adb","exec-out","screencap","-p"],check=True,stdout=subprocess.PIPE).stdout)
def tap(x,y): adb("shell","input","tap",str(x),str(y)); time.sleep(.7)

if not APK.exists():
    raise SystemExit(f"APK not found: {APK}")
adb("wait-for-device")
print(adb("install","-r",str(APK)))
adb("logcat","-c")
adb("shell","am","force-stop",PKG)
print(adb("shell","am","start","-W","-n",ACT))
time.sleep(3); shot("01-cold-launch")
# Dismiss/advance tutorial overlays if present, then exercise controls.
for _ in range(5): tap(606,270)
shot("02-tutorial-advanced")
tap(120,485); tap(35,340); time.sleep(3); shot("03-gather")
tap(360,485); tap(606,270); shot("04-wall")
tap(845,485); shot("05-paused"); tap(845,485)
tap(1085,485); tap(1085,485); time.sleep(12); shot("06-accelerated")
# Force-stop/cold relaunch is the persistence boundary.
adb("shell","am","force-stop",PKG); time.sleep(1)
print(adb("shell","am","start","-W","-n",ACT)); time.sleep(3); shot("07-cold-relaunch")
logs=adb("logcat","-d","-v","brief")
fatal=[line for line in logs.splitlines() if "FATAL EXCEPTION" in line or "AndroidRuntime" in line]
(OUT/"fatal.log").write_text("\n".join(fatal)+("\n" if fatal else ""))
if fatal: raise SystemExit("Fatal Android logs found; see "+str(OUT/"fatal.log"))
print("PASS: install, launch, touch controls, force-stop, cold relaunch; screenshots:",OUT)
