#!/usr/bin/env bash
set -euo pipefail
: "${AMAZINGCAT_TOKEN:?Set your browser-issued token}"
# initialize: show headers and save them; the response body goes to initialize.json.
curl --fail-with-body 'https://mcp.amazingcat.net/mcp' -D - -o initialize.json \
  -H "Authorization: Bearer $AMAZINGCAT_TOKEN" \
  -H 'Accept: application/json, text/event-stream' -H 'Content-Type: application/json' \
  --data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"cat-curl","version":"1"}}}' \
  | tee initialize.headers
# Copy the server's response header into a variable.
export MCP_SESSION_ID="$(awk 'tolower($1)=="mcp-session-id:" {gsub("\r","",$2);print $2}' initialize.headers)"
test -n "$MCP_SESSION_ID" || exit 1
curl --fail-with-body 'https://mcp.amazingcat.net/mcp' \
  -H "Authorization: Bearer $AMAZINGCAT_TOKEN" -H "Mcp-Session-Id: $MCP_SESSION_ID" \
  -H 'MCP-Protocol-Version: 2025-06-18' \
  -H 'Accept: application/json, text/event-stream' -H 'Content-Type: application/json' \
  --data '{"jsonrpc":"2.0","method":"notifications/initialized"}'
curl --fail-with-body -o law.json 'https://mcp.amazingcat.net/mcp' \
  -H "Authorization: Bearer $AMAZINGCAT_TOKEN" -H "Mcp-Session-Id: $MCP_SESSION_ID" \
  -H 'MCP-Protocol-Version: 2025-06-18' \
  -H 'Accept: application/json, text/event-stream' -H 'Content-Type: application/json' \
  --data '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"law_find","arguments":{"query":"Воздушный кодекс","limit":5}}}'
python3 - <<'PYCODE'
import json
from pathlib import Path
text=Path('law.json').read_text()
if text.lstrip().startswith('{'):
    reply=json.loads(text)
else:
    for event in text.replace('\r\n', '\n').split('\n\n'):
        data=[line[5:].lstrip(' ') for line in event.splitlines() if line.startswith('data:')]
        if not data: continue
        message=json.loads('\n'.join(data))
        if message.get('id')==2:
            reply=message
            break
    else: raise RuntimeError('No matching JSON-RPC response')
if reply.get('id')!=2: raise RuntimeError('No matching JSON-RPC response')
if reply.get('error'): raise RuntimeError(reply['error'])
result=reply['result']
if result.get('isError'): raise RuntimeError(result)
law=json.loads(next(b['text'] for b in result['content'] if b['type']=='text'))
print(json.dumps({'tool':'law_find','candidates':len(law['candidates']),'first':law['candidates'][0]['name']},ensure_ascii=False))
PYCODE
