# Hermes REAL binary vs Anthropic DIRECT (API key) — Phase A: 4 rapid turns.
# base_url -> local logging proxy (18081) which records markers + usage.
# FAIL-LOUD: every turn must produce a NEW proxy line and growing history.
import json, os, re, sys

KEY = os.environ['ANTHROPIC_API_KEY']  # [sanitized for publication: originally read from a local .env file]
os.environ['ANTHROPIC_API_KEY'] = KEY
# Hermes token resolution prefers Claude Code's OAuth creds (~/.claude) over
# ANTHROPIC_API_KEY. ANTHROPIC_TOKEN is priority #1 — set it to the API key so
# the adapter uses it (sk-ant-api03 prefix → x-api-key header, not Bearer).
os.environ['ANTHROPIC_TOKEN'] = KEY

from run_agent import AIAgent

LOG = 'anth-proxy-log.jsonl'
def proxy_lines():
    try:
        raw = open(LOG, encoding='utf-8').read().strip()
        return raw.split('\n') if raw else []
    except FileNotFoundError:
        return []

def filler(t):
    return ''.join(f"row {t}-{i} a={(i*7919)%104729} b={(i*104729)%7919} c={i%13}; " for i in range(260))

agent = AIAgent(base_url='http://127.0.0.1:18081', api_key=KEY,
                model='claude-sonnet-4-5-20250929', provider='anthropic')

history, results, prev_msgs = [], [], 0

def do_turn(t, label):
    global prev_msgs
    n0 = len(proxy_lines())
    idle_tag = ' AFTER IDLE' if 'idle' in label else ''
    user_msg = f"TURN {t}{idle_tag}: Reply with exactly OK{t}. Ignore: {filler(t)}"
    r = agent.run_conversation(user_msg, conversation_history=list(history))
    lines = proxy_lines()
    if len(lines) <= n0:
        print(f"FATAL {label}: NO new proxy line — Hermes bypassed the proxy (base_url not honored for anthropic). INVALID.", flush=True)
        sys.exit(2)
    last = json.loads(lines[-1])
    if not last.get('usage') or last.get('status') != 200:
        print(f"FATAL {label}: call errored (status={last.get('status')}). INVALID.", flush=True)
        sys.exit(4)
    msgs = last.get('nMessages') or 0
    if msgs <= prev_msgs:
        print(f"FATAL {label}: history not growing (msgs={msgs} prev={prev_msgs}). INVALID.", flush=True)
        sys.exit(3)
    prev_msgs = msgs
    u = last.get('usage') or {}
    row = {'label': label, 'msgs': msgs,
           'markers': [m.get('ttl') for m in (last.get('markers') or [])],
           'input_tokens': u.get('input_tokens'),
           'cache_read': u.get('cache_read_input_tokens'),
           'cache_write': u.get('cache_creation_input_tokens'),
           'write_5m': (u.get('cache_creation') or {}).get('ephemeral_5m_input_tokens'),
           'write_1h': (u.get('cache_creation') or {}).get('ephemeral_1h_input_tokens'),
           'ts': last.get('ts')}
    results.append(row)
    text = None
    if isinstance(r, dict):
        for k in ('response', 'final_response', 'content', 'text', 'result'):
            v = r.get(k)
            if isinstance(v, str) and v.strip(): text = v; break
    history.append({'role': 'user', 'content': user_msg})
    history.append({'role': 'assistant', 'content': (text or f"OK{t}")[:200]})
    print(f"{label}: msgs={msgs} input={row['input_tokens']} read={row['cache_read']} write={row['cache_write']} (5m={row['write_5m']} 1h={row['write_1h']}) markers={row['markers']}", flush=True)

for t in range(1, 5):
    do_turn(t, f'turn{t}')

json.dump({'phase': 'A', 'prev_msgs': prev_msgs, 'history': history, 'turns': results},
          open('hermes-anth-state.json', 'w'), indent=1)
print('PHASE A COMPLETE', flush=True)
