"""Check the note server over stdio; needs Python 3 and a built binary.

Usage: python3 verify.py ./bin/approved-notes
"""
import json
from pathlib import Path
import subprocess
import sys

binary = Path(sys.argv[1] if len(sys.argv)>1 else 'bin/approved-notes').resolve()
messages = [
    {'jsonrpc':'2.0','id':1,'method':'initialize','params':{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'notes-check','version':'1'}}},
    {'jsonrpc':'2.0','method':'notifications/initialized'},
    {'jsonrpc':'2.0','id':2,'method':'tools/list','params':{}},
]
cases = [
    ('known', {'collection':'approved','id':'release-checklist'}, None),
    ('missing', {'collection':'approved','id':'missing-note'}, 'not_found'),
    ('malformed', {'collection':'approved','id':'../private'}, 'invalid_argument'),
    ('denied', {'collection':'private','id':'release-checklist'}, 'permission_denied'),
    ('unknown-field', {'collection':'approved','id':'release-checklist','override':'private'}, 'invalid_argument'),
]
for ident, (_, arguments, _) in enumerate(cases,3):
    messages.append({'jsonrpc':'2.0','id':ident,'method':'tools/call','params':{'name':'note_lookup','arguments':arguments}})
result = subprocess.run([str(binary)],input=''.join(json.dumps(m)+'\n' for m in messages),capture_output=True,text=True,timeout=15)
assert result.returncode==0, result.stderr
replies = [json.loads(line) for line in result.stdout.splitlines()]
by_id = {reply.get('id'):reply for reply in replies}
assert 'result' in by_id[1], by_id[1]
assert [t['name'] for t in by_id[2]['result']['tools']]==['note_lookup']
for ident,(name,_,code) in enumerate(cases,3):
    reply=by_id[ident]
    value=reply.get('result',{})
    if code:
        assert value.get('isError') and value.get('structuredContent',{}).get('code')==code,(name,reply)
    else:
        assert not value.get('isError'),reply
        note=value.get('structuredContent',{})
        assert note=={'id':'release-checklist','title':'Release review','text':'Review the change, run the checks, and record the outcome before publishing.'},reply
    print(name+': passed')
print('Initialization, discovery, lookup and four refusals passed; stdout is JSON-RPC only.')
