import datetime,hashlib,json,subprocess,time,urllib.request
from pathlib import Path
folder=Path(__file__).parent
start=time.monotonic()
def get(path):
 with urllib.request.urlopen('http://127.0.0.1:18081'+path,timeout=5) as response:return json.load(response)
with (folder/'idle-samples.jsonl').open('w',buffering=1) as out:
 for i in range(61):
  data={'time':datetime.datetime.now(datetime.timezone.utc).isoformat(),'elapsed_s':round(time.monotonic()-start,1)}
  try:
   devices=get('/devices'); d=next(item for item in devices if item['device_id']=='esp32s3-28848543a200')
   status=get('/api/status'); agent=next((item for item in status['pi_sessions'] if item['session_id']=='01a0fcd2-7b96-77fb-a57a-40bbfb9fe5da'),{})
   service=subprocess.check_output(['systemctl','--user','show','device-gateway.service','-p','MainPID','-p','NRestarts'],text=True).strip()
   data.update(online=d['online'],target=d['target'],speech_mode=d['speech_mode'],last_event=d['last_event'],service=service,agent_state=agent.get('state'),final_bytes=len(agent.get('final_text','').encode()))
  except Exception as error:data['error']=type(error).__name__
  out.write(json.dumps(data)+'\n')
  if i%6==0:print(json.dumps(data),flush=True)
  if i<60:time.sleep(5)
