import sys, json, time
sys.path.insert(0,'/tmp')
from amd_lib import session, call

def get_status(sid): return call(sid,"auth_status",{})

sid = session()
# respect cooldown
st = get_status(sid)
cds = st.get("cooldowns",{})
if cds:
    mins = max((v.get("minsLeft",0) for v in cds.values()), default=0)
    if mins>0:
        print(f"cooldown {mins}m, sleeping", flush=True)
        time.sleep((mins+2)*60)
        sid = session()

for attempt in range(5):
    try:
        r = call(sid,"get_updated_patients",{"lastmodifieddate":"2026-04-01"})
        break
    except Exception as e:
        msg=str(e)
        if "cool" in msg.lower() or "rate" in msg.lower() or "limit" in msg.lower():
            try:
                st=get_status(sid); cds=st.get("cooldowns",{})
                mins=max((v.get("minsLeft",0) for v in cds.values()),default=60)
            except: mins=60
            print(f"rate-limited, sleeping {mins}m", flush=True)
            time.sleep((mins+2)*60); sid=session()
        else:
            print("err",msg[:80]); time.sleep(5)
else:
    raise SystemExit("could not fetch contacts")

rows = r.get("rows", [])
json.dump(rows, open("/tmp/updated_patients.json","w"))
print("updated_patients rows:", len(rows))
if rows:
    print("keys:", list(rows[0].keys()))
