"""Checkpointed, read-only report inventory through the adapter RPC."""
from __future__ import annotations
import argparse, json, urllib.request
from pathlib import Path

def call(url, method, payload):
    req=urllib.request.Request(url.rstrip('/')+'/rpc', data=json.dumps({'method':method,'payload':payload}).encode(), headers={'Content-Type':'application/json'})
    with urllib.request.urlopen(req, timeout=30) as r: return json.loads(r.read())

def main():
    p=argparse.ArgumentParser(); p.add_argument('--url',required=True); p.add_argument('--base-id',required=True); p.add_argument('--output',type=Path,required=True); a=p.parse_args()
    state=json.loads(a.output.read_text('utf-8')) if a.output.exists() else {'schema':'onec_report_inventory.v1','reports':{}}
    names=list(state['reports'])
    if not names:
        listed=call(a.url,'metadata.objects.list',{'base_id':a.base_id,'kind':'Report','limit':500})
        names=[item.get('name') for item in listed.get('objects',[])]
    for name in names:
        if not name or state['reports'].get(name, {}).get('status') == 'ok': continue
        try: state['reports'][name]=call(a.url,'report.inspect',{'base_id':a.base_id,'report':name,'timeout_seconds':60})
        except Exception as exc: state['reports'][name]={'status':'transport_error','diagnostics':str(exc)}
        a.output.parent.mkdir(parents=True,exist_ok=True); a.output.write_text(json.dumps(state,ensure_ascii=False,indent=2),encoding='utf-8')
if __name__=='__main__': main()
