"""Real Storage Host consumer: put/get, then a separate-host reopen check."""
import argparse,json,subprocess
from pathlib import Path

parser=argparse.ArgumentParser()
parser.add_argument('--host',required=True,help='Prepared Storage Runtime Host DLL')
parser.add_argument('--provider',required=True,help='Prepared provider DLL with its dependencies')
parser.add_argument('--kind',choices=['memory','sqlite'],default='memory')
parser.add_argument('--database',help='SQLite file in a private test directory')
parser.add_argument('--evidence',help='Optional output JSON with requests and responses')
args=parser.parse_args()
if args.kind=='sqlite' and not args.database:parser.error('SQLite requires --database')
config={} if args.kind=='memory' else {'path':str(Path(args.database).resolve())}
def request(id,action,**fields):
    return dict(schemaVersion='junexis.storage.runtime/0.1',requestId=id,action=action,**fields)
def opening():return request('open','open',providerId=args.kind,bindingId='example',config=config)
def operation(id,name,effect,**fields):return request(id,'invoke',bindingId='example',operation=name,effect=effect,input=dict(bucket='measurements',key='room-1',**fields))
def execute(requests):
    result=subprocess.run(['dotnet',str(Path(args.host).resolve()),'--provider',str(Path(args.provider).resolve())],input=''.join(json.dumps(r)+'\n' for r in requests),capture_output=True,text=True,timeout=30)
    if result.returncode:raise RuntimeError(result.stderr)
    rows=[json.loads(line) for line in result.stdout.splitlines() if line.strip()]
    if len(rows)!=len(requests):raise RuntimeError('Incomplete response sequence')
    return {r['requestId']:r for r in rows}
first=[request('hello','handshake',supportedAbi=['junexis.storage.runtime/0.1']),opening(),operation('put','put','write',payload={'celsius':21.0}),operation('get','get','read'),request('close','close',bindingId='example'),request('stop','shutdown')]
responses=execute(first)
if not all(r['success'] for r in responses.values()):raise RuntimeError(json.dumps(responses))
value=responses['get']['result']['value']['payload']['celsius']
assert value==21.0
print(f'{args.kind}: zapisano room-1 = 21.0')
print(f'{args.kind}: odczytano room-1 = {value:.1f}')
second=[opening(),operation('get-again','get','read'),request('stop','shutdown')]
reopened=execute(second);r=reopened['get-again']
if args.kind=='memory':
    assert not r['success'] and r['error']['errorClass']=='not-found',r
    print('memory: nowy host i binding sa puste')
else:
    assert r['success'] and r['result']['value']['payload']['celsius']==21.0,r
    print('sqlite: nowy host odczytal 21.0 z tego samego pliku')
if args.evidence:
    Path(args.evidence).write_text(json.dumps({'kind':args.kind,'requests':first,'responses':responses,'reopen':reopened,'real_host_process':True,'fresh_build':False},ensure_ascii=False,indent=2),encoding='utf-8')
