from ops import *

trial=json.loads((HERE/'trial-result.json').read_text())
begin=float(trial['begin_wall'])
sql=f"SELECT coalesce(json_agg(t),'[]') FROM (SELECT event_id, relative_path, artifact_state, delivery_state, error, attempts, payload->>'scenario' AS scenario, payload->>'cameraId' AS camera, payload->'crowd' AS crowd FROM contextra_event_artifacts WHERE confirmed_at >= {begin} ORDER BY confirmed_at) t;"
def query():
    return json.loads(cmd(['docker','exec','-i','contextra-postgresql-1','sh','-c',
        'exec psql -X -qAt -U "$POSTGRES_USER" -d "$POSTGRES_DB"'],input=sql))
end=time.monotonic()+90
while True:
    rows=query()
    crowd=[r for r in rows if r['scenario']=='CROWD']
    if crowd and all(r['artifact_state'] in ('READY','FAILED','EXPIRED') and r['delivery_state'] not in ('PENDING','RETRY','SENDING') for r in crowd):
        break
    if time.monotonic()>end:
        break
    time.sleep(2)
save('artifact-observation.json',dict(rows=rows,crowd=crowd))
container=inspect('contextra-analytics-1')
env=dict(v.split('=',1) for v in container['Config']['Env'])
root=env['CONTEXTRA_ARTIFACT_ROOT']
mount=max((m for m in container['Mounts'] if root==m['Destination'] or root.startswith(m['Destination']+'/')),
          key=lambda m:len(m['Destination']))
host_root=Path(mount['Source'])/Path(root).relative_to(mount['Destination'])
checks=[]
for row in crowd:
    if row['artifact_state']!='READY':
        continue
    folder=host_root/row['relative_path']
    clip=folder/'clip.mp4'
    output=cmd(['ffprobe','-v','error','-count_frames','-show_entries',
        'stream=codec_name,width,height,nb_read_frames:format=duration','-of','json',str(clip)],timeout=30)
    probe=json.loads(output)
    cmd(['ffmpeg','-v','error','-threads','2','-i',str(clip),'-f','null','-'],timeout=40)
    timestamps=json.loads(cmd(['ffprobe','-v','error','-select_streams','v:0','-show_entries',
        'frame=best_effort_timestamp_time','-of','json',str(clip)],timeout=30))
    pts=[float(p['best_effort_timestamp_time']) for p in timestamps['frames']]
    assert pts and all(b>a for a,b in zip(pts,pts[1:]))
    checks.append(dict(event=row['event_id'],camera=row['camera'],probe=probe,
        monotonic_pts=True,decode='PASS',thumbnail=str(folder/'thumbnail.jpg'),clip=str(clip)))
save('artifact-media-verification.json',checks)
print(json.dumps(dict(crowd=crowd,media=checks),ensure_ascii=False),flush=True)
