#!/usr/bin/env python3
"""Poll Hevy state via ADB screenshot + vision API. Updates backend."""
import subprocess
import time
import requests
import sys
import os

BACKEND = "http://localhost:8420"
SCREENSHOT_PATH = "/tmp/hevy-live.png"

def take_screenshot():
    try:
        result = subprocess.run(
            ["adb", "exec-out", "screencap", "-p"],
            capture_output=True, timeout=10
        )
        if result.returncode == 0 and len(result.stdout) > 1000:
            with open(SCREENSHOT_PATH, "wb") as f:
                f.write(result.stdout)
            return True
    except Exception as e:
        print(f"Screenshot error: {e}", file=sys.stderr)
    return False

def main():
    print("Hevy Poller started. Taking screenshots every 3s...")
    while True:
        try:
            if take_screenshot():
                # Check if backend is alive
                r = requests.get(f"{BACKEND}/api/hevy/live", timeout=5)
                print(f"  Screenshot OK, state: {r.json().get('restTimer', '?')}")
            else:
                print("  Screenshot FAILED")
        except Exception as e:
            print(f"  Error: {e}")
        time.sleep(3)

if __name__ == "__main__":
    main()
