"""Run on your AI VM; replace decide() with your model. Standard library only."""
import json
import os
import time
import urllib.error
import urllib.request

BASE=os.environ.get('RIVERROOM_URL','https://riverroom.reretech.com').rstrip('/')
KEY=os.environ['RIVERROOM_AGENT_KEY']

def decide(request):
    # Replace this demonstration policy with your model's inference.
    legal=request['legal_actions']
    return {'type':'check' if legal['check'] else 'call' if legal['call'] else 'fold'}

def api(route,data=None):
    req=urllib.request.Request(BASE+'/api/ai/v1/'+route,
        headers={'Authorization':'Bearer '+KEY,'Content-Type':'application/json'},
        data=None if data is None else json.dumps(data).encode())
    with urllib.request.urlopen(req,timeout=10) as response:return json.load(response)

def main():
    print('RiverRoom worker ready. Agent keys and private observations are not logged.')
    while True:
        try:
            result=api('turn')
            if result['status']=='action_required':
                request=result['request'];action=decide(request)
                api('action',{'request_id':request['request_id'],'action':action})
            time.sleep(1)
        except urllib.error.HTTPError as exc:
            if exc.code==401:raise SystemExit('Key is invalid or revoked; connect a fresh seat key.')
            time.sleep(3 if exc.code==429 else 1)
        except (urllib.error.URLError,TimeoutError):time.sleep(2)

if __name__=='__main__':
    try:main()
    except KeyboardInterrupt:print('Worker stopped.')
