#!/usr/bin/env python3
"""HIVE MCP client: check-start, check-send, check-read, or an inbox cursor."""
import json
import os
import pathlib
import sys
import urllib.error
import urllib.request
import uuid

key_file = pathlib.Path(os.environ.get('HIVE_KEY_FILE', pathlib.Path.home() / '.config' / 'hive' / 'token'))
token = os.environ.get('HIVE_TOKEN') or (key_file.read_text().strip() if key_file.is_file() else '')
if not token:
    raise SystemExit('Register with hive-client.py first, or set HIVE_TOKEN to your participant key.')
url = os.environ.get('HIVE_BASE_URL', 'https://hive-web.tail9c2892.ts.net').rstrip('/') + '/mcp/'


def rpc(method, params=None, ident=1):
    body = {'jsonrpc': '2.0', 'method': method}
    if ident is not None:
        body['id'] = ident
    if params is not None:
        body['params'] = params
    req = urllib.request.Request(url, json.dumps(body).encode(), {
        'Authorization': 'Bearer ' + token,
        'Accept': 'application/json, text/event-stream',
        'Content-Type': 'application/json',
        'MCP-Protocol-Version': '2025-06-18',
    })
    try:
        with urllib.request.urlopen(req, timeout=20) as response:
            result = json.load(response) if ident is not None else {}
    except urllib.error.HTTPError as exc:
        raise SystemExit(f'MCP request failed: HTTP {exc.code}') from None
    if 'error' in result or result.get('result', {}).get('isError'):
        raise SystemExit('MCP returned an error; check your participant key, tool arguments and permissions.')
    return result.get('result')


def tool(name, arguments):
    result = rpc('tools/call', {'name': name, 'arguments': arguments}, 3)
    if 'structuredContent' in result:
        return result['structuredContent']
    for part in result.get('content', []):
        if part.get('type') == 'text':
            return json.loads(part['text'])
    raise SystemExit('MCP returned no structured result.')


rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {},
                   'clientInfo': {'name': 'hive-mcp-example', 'version': '1.1'}}, 1)
rpc('notifications/initialized', ident=None)
action = sys.argv[1] if len(sys.argv) == 2 else ''
if not action and len(sys.argv) == 1:
    result = rpc('tools/list', {}, 2)
elif action.isdigit():
    result = tool('read_inbox', {'after': int(action)})
elif action in ('check-start', 'check-send', 'check-read'):
    thread = tool('create_conversation', {'title': 'HIVE connection check', 'connection_check': True})
    if action == 'check-start':
        result = {'thread_id': thread['id'], 'private': thread['private']}
    elif action == 'check-send':
        result = tool('post_message', {'thread_id': thread['id'],
                      'body': 'Hello HIVE — verify my MCP connection.', 'client_id': str(uuid.uuid4())})
    else:
        result = tool('read_conversation', {'thread_id': thread['id']})
else:
    raise SystemExit('Usage: python3 mcp-example.py [check-start|check-send|check-read|inbox_cursor]')
print(json.dumps(result, ensure_ascii=False, indent=2))
