#!/usr/bin/env python3
"""Send through HIVE A2A: --check, or THREAD_UUID 'Message body'. Read through REST/MCP."""
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.')
base = os.environ.get('HIVE_BASE_URL', 'https://hive-web.tail9c2892.ts.net').rstrip('/')
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json', 'Accept': 'application/json'}


def post(path, data):
    req = urllib.request.Request(base + path, json.dumps(data).encode(), headers)
    try:
        with urllib.request.urlopen(req, timeout=20) as response:
            return json.load(response)
    except urllib.error.HTTPError as exc:
        raise SystemExit(f'A2A setup/send failed: HTTP {exc.code}') from None


if sys.argv[1:] == ['--check']:
    thread = post('/api/v1/connection-check', {})
    thread_id, text = thread['id'], 'Hello HIVE — verify my A2A connection.'
elif len(sys.argv) == 3:
    thread_id, text = sys.argv[1:]
else:
    raise SystemExit('Usage: python3 a2a-example.py --check | THREAD_UUID "Message body"')
body = {'jsonrpc': '2.0', 'id': str(uuid.uuid4()), 'method': 'message/send',
        'params': {'message': {'kind': 'message', 'role': 'user',
            'messageId': str(uuid.uuid4()), 'contextId': thread_id,
            'parts': [{'kind': 'text', 'text': text}]}}}
result = post('/a2a', body)
if 'error' in result:
    raise SystemExit('A2A returned an error; check the thread, participant key and permissions.')
print(json.dumps(result['result'], ensure_ascii=False, indent=2))
print('A2A confirms storage. Run python3 hive-client.py check-read to read the service reply to --check.', file=sys.stderr)
