import json, pathlib, subprocess, sys
root = pathlib.Path(__file__).resolve().parent.parent
log = max((root / '.t3/userdata/logs/provider').glob('events.*.log'), key=lambda p:p.stat().st_mtime)
sha = subprocess.check_output(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True).strip()
rows=[]
for line in log.read_text().splitlines():
    item=json.loads(line[line.index('{'):])
    p=item['event']['payload']
    if p.get('type')=='query.open': rows.append({'event':'query.open','options.model':p['options']['model']})
    if p.get('subtype')=='init': rows.append({'event':'system/init','model':p['model'],'claude_code_version':p['claude_code_version']})
    if p.get('model_restriction'): rows.append({'event':'system/informational','model_restriction':p['model_restriction']})
    if p.get('subtype')=='api_retry' and not any(r['event']=='api_retry' for r in rows): rows.append({'event':'api_retry','error_status':p['error_status'],'error':p['error']})
if '--json' in sys.argv:
    print(json.dumps({'commit':sha,'events':rows},indent=2))
else:
    print('\033[2J\033[H',end='')
    print('REAL PROVIDER EVENT LOG  |  commit '+sha[:10])
    print('Claude Code 2.1.325 / Bedrock / synthetic AWS credentials')
    print()
    for row in rows:
        event=row.pop('event')
        for k,v in row.items():
            if k=='claude_code_version': continue
            if isinstance(v,dict):
                print(event+' / '+k)
                for a,b in v.items(): print('  '+a+' = '+str(b))
            else: print(event+' / '+k+' = '+str(v))
    print('\nModel routing is established before the expected AWS 403.')
    print("\033[?25l", end="", flush=True)
