"""Controller-only deterministic witness. Receives public tools/context, no state/oracle.""" from datetime import datetime from decimal import Decimal from copy import deepcopy def solve(number,call,context): limitations=[] def load(collection,predicate=None): directory=call('list_'+collection,{})['result']['items'] ids=[r['id'] for r in directory if predicate is None or predicate(r)] if not ids:return [] response=call('read_'+collection,{'ids':ids})['result'] limitations.extend({'resource':collection+'/'+r['id'],'reason':r['code']} for r in response['unavailable']) return [deepcopy(r['data']) for r in response['items']] def stopped():return {'report':None,'limitations':sorted(limitations,key=lambda x:(x['resource'],x['reason']))} if number==1: r=load('routes',lambda h:h['id']==context['route_id']);d=load('dispatch_notes',lambda h:h['id']==context['route_id']) if limitations:return stopped() parse=lambda s:datetime.fromisoformat(s.replace('Z','+00:00')) if tuple(parse(r[0][k]) for k in ('time_window_start','time_window_end'))!=tuple(parse(d[0][k]) for k in ('start','end')): limitations.append({'resource':'routes/'+context['route_id'],'reason':'CONFLICTING_RECORDS'});return stopped() result={'route_id':context['route_id'],'window_start':d[0]['start'],'window_end':d[0]['end']} elif number==2: event=load('appointments',lambda h:h['id']==context['event_id']);confirmation=load('provider_messages',lambda h:h['id']==context['confirmation_id']) if limitations:return stopped() e,c=event[0],confirmation[0] if any(e[k]!=c[k] for k in ('date','start_time','location')): limitations.append({'resource':'appointments/'+context['event_id'],'reason':'CONFLICTING_RECORDS'});return stopped() result={'event':e,'clinician':c['clinician'],'confirmation_id':context['confirmation_id']} elif number in (3,50): sessions=load('sessions',lambda h:h['index']['start_time'][:10]==context['date'] and int(h['index']['start_time'][11:13])>=context['start_hour']);notes=load('journal_notes') if limitations:return stopped() sessions.sort(key=lambda r:(r['start_time'],r['usage_id'])) relevant=[n for n in notes if n['late_night_relevance'] and any(s['content_type'] in n['supported_content_types'] for s in sessions)] if number==3: groups=[] for kind in context['content_types']: ss=[s for s in sessions if s['content_type']==kind] groups.append({'content_type':kind,'minutes':sum(s['duration_minutes'] for s in ss),'usage_ids':sorted(s['usage_id'] for s in ss), 'factor_ids':sorted(n['evidence_id'] for n in relevant if ss and kind in n['supported_content_types'])}) result={'date':context['date'],'categories':groups,'notes':sorted(relevant,key=lambda n:n['evidence_id'])} else:result={'sessions':sessions,'factors':sorted(relevant,key=lambda n:n['evidence_id'])} elif number==4: directory=call('list_sleep_records',{})['result']['items'];groups={} for h in directory: if context['from']<=h['index']['night']<=context['through']:groups.setdefault(h['index']['origin_night_id'],[]).append(h) selected={max(v,key=lambda h:(h['index']['source']=='oura',h['index']['imported_at']))['id'] for v in groups.values()} rows=load('sleep_records',lambda h:h['id'] in selected);by_night={} if limitations:return stopped() for row in rows:by_night.setdefault(row['night'],[]).append(row) kept=[] for night in sorted(by_night): options=by_night[night];direct=[r for r in options if r['source']=='oura'] kept.append(max(direct or options,key=lambda r:r['imported_at'])) mean=lambda field:round(float(sum(Decimal(str(r[field])) for r in kept)/len(kept)),1) result={'nights':kept,'mean_sleep_minutes':mean('total_sleep_minutes'),'mean_efficiency_percent':mean('efficiency_percent'), 'mean_rem_share_percent':mean('rem_share_percent'),'below_target_nights':sum(r['efficiency_percent']=r['distance_km'] and d['max_payload_kg']>=r['payload_kg'] and parse(d['available_from'])<=parse(r['time_window_start']) and parse(d['available_until'])>=parse(r['time_window_end']):ids.append(d['drone_id']) result={'route_id':r['route_id'],'suitable_drone_ids':sorted(ids),'weather':weather[0]} elif number==54: portfolios=load('portfolios',lambda h:h['id']==context['portfolio_id']) directory=call('list_orders',{})['result']['items'];candidates=[h for h in directory if h['index']['symbol']==context['symbol']] latest=max(candidates,key=lambda h:datetime.fromisoformat(h['index']['created_at'].replace('Z','+00:00'))) orders=load('orders',lambda h:h['id']==latest['id']) if limitations:return stopped() result={'currency':portfolios[0]['currency'],'holdings':[{k:r[k] for k in ('symbol','quantity','market_value','unrealized_pl')} for r in sorted(portfolios[0]['holdings'],key=lambda r:r['symbol'])],'latest_order':orders[0]} elif number==55: orders=load('orders') if limitations:return stopped() result={'orders':sorted(orders,key=lambda r:(r['order_date'],r['id']))} elif number==56: notes=load('geometry_notes') if limitations:return stopped() notes.sort(key=lambda r:r['shape']);a,b=notes diff=round(abs(a['longest_diagonal']-b['longest_diagonal']),3) result={'measurements':notes,'larger_shape':max(notes,key=lambda r:r['longest_diagonal'])['shape'] if diff else None,'difference':diff} elif number==57: analyses=load('saved_analyses',lambda h:h['index']['dataset_id']==context['dataset_id']) if limitations:return stopped() result=analyses[0] for k in ('themes','image_categories','representative_images'):result[k]=sorted(result[k]) elif number==58: playlists=load('playlists',lambda h:h['title']==context['playlist_name']);saved=load('saved_tracks') if limitations:return stopped() saved_ids={r['track_id'] for r in saved[0]};p=playlists[0] result={'playlist_id':p['playlist_id'],'tracks':[dict(track_id=t['track_id'],title=t['title'],artist_names=t['artist_names'],saved_individually=t['track_id'] in saved_ids) for t in p['tracks']]} elif number==59: directory=call('list_forecasts',{})['result']['items'];picked=[] for field in context['fields']: options=[h for h in directory if h['index']['year']==context['year'] and all(h['index'][k]==v for k,v in field.items())] picked.append(max(options,key=lambda h:datetime.fromisoformat(h['index']['created_at'].replace('Z','+00:00')))['id']) forecasts=load('forecasts',lambda h:h['id'] in picked) if limitations:return stopped() result={'forecasts':sorted(forecasts,key=lambda r:(r['farm_id'],r['field_id']))} elif number==60: measurements=load('measurements',lambda h:h['id'] in context['record_ids']) if limitations:return stopped() measurements.sort(key=lambda r:r['record_id']);a,b=measurements if (a['part_id'],a['revision'])!=(b['part_id'],b['revision']): limitations.append({'resource':'measurements/'+b['record_id'],'reason':'CONFLICTING_RECORDS'});return stopped() result={'records':measurements,**{side+'_agrees':all(a[side][k]==b[side][k] for k in ('value','unit')) for side in ('long_side','short_side')}} else:raise ValueError(number) return {'report':result,'limitations':[]}