#!/usr/bin/env python3
"""Selective named-tool evidence retrieval; --bulk retains the legacy full-snapshot path."""
import argparse, hashlib, json, re, ssl
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin, urlparse
from urllib.request import Request, urlopen
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('base_url');p.add_argument('--tool',action='append');p.add_argument('--name');p.add_argument('--category');p.add_argument('--function');p.add_argument('--integrations',action='store_true');p.add_argument('--bulk',action='store_true',help='Use the legacy hash-checked full-snapshot endpoints');a=p.parse_args()
base=a.base_url.rstrip('/')+'/'
if urlparse(base).scheme not in ('https','http'):p.error('Use an HTTP(S) API base URL')
if a.tool and (len(a.tool)>10 or len(set(a.tool))!=len(a.tool) or any(not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,127}',tool) for tool in a.tool)):p.error('--tool accepts 1..10 unique lowercase tool IDs')
accounting={'http_requests_attempted':0,'http_responses_observed':0,'response_bytes_observed':0,'failed_requests':0,'failed_response_bytes_observed':0,'requests_without_response_bytes':0}
def download(url,missing_ok=False):
    request=Request(url,headers={'User-Agent':'StackMapSnapshotClient/1.0','Accept':'application/json'})
    accounting['http_requests_attempted']+=1
    try:
        with urlopen(request,timeout=30) as response:raw=response.read();accounting['http_responses_observed']+=1;accounting['response_bytes_observed']+=len(raw);return raw
    except HTTPError as error:
        raw=error.read();accounting['http_responses_observed']+=1;accounting['response_bytes_observed']+=len(raw);accounting['failed_requests']+=1;accounting['failed_response_bytes_observed']+=len(raw)
        if missing_ok and error.code==404:return None
        raise SystemExit('Snapshot download failed: '+str(error)) from error
    except URLError as error:
        accounting['failed_requests']+=1;accounting['requests_without_response_bytes']+=1
        if isinstance(error.reason,ssl.SSLCertVerificationError):
            raise SystemExit('TLS certificate verification failed. Configure trusted CA certificates for your Python installation; do not disable TLS verification.') from error
        raise SystemExit('Snapshot download failed: '+str(error)) from error
def legacy():
    index=json.loads(download(urljoin(base,'index.json')))
    if index.get('schema')!='stackmap.public-snapshot.v1':raise SystemExit('Unsupported API schema')
    def load(name):
        endpoint=index['endpoints'][name];raw=download(urljoin(base,endpoint['href']))
        if hashlib.sha256(raw).hexdigest()!=endpoint['sha256']:raise SystemExit('Snapshot changed or endpoint hash mismatch; refresh index')
        value=json.loads(raw)
        if value['snapshot']!=index['snapshot']:raise SystemExit('Mixed snapshots')
        return value
    catalog=load('catalog');tools=catalog['tools']
    if a.tool:tools=[t for t in tools if t['tool_id'] in set(a.tool)]
    if a.category:tools=[t for t in tools if a.category in t.get('capability_slugs',[]) or t.get('primary_capability_slug')==a.category]
    if a.name:tools=[t for t in tools if a.name.casefold() in (t.get('name','')+' '+t.get('short_description','')).casefold()]
    ids={t['tool_id'] for t in tools};result={'snapshot':index['snapshot'],'tools':tools,'query_execution':'client_side_bulk_filter_legacy','accounting':accounting}
    if a.function:
        rows=[r for r in load('functions')['assertions'] if r['active_in_export'] and r['tool_id'] in ids and r['key']==a.function and (not a.category or r['capability_slug']==a.category)]
        result['assertions']=rows;result['tools_with_no_matching_assertion']=sorted(ids-{r['tool_id'] for r in rows})
    if a.integrations:result['integrations']=[e for e in load('integrations')['edges'] if e['source_tool_id'] in ids or e['target_tool_id'] in ids]
    return result
def selective(tool_ids):
    packs=[];snapshot=None
    for tool_id in tool_ids:
        lookup_raw=download(urljoin(base,'lookups/'+tool_id+'.json'),missing_ok=True)
        if lookup_raw is None:return None
        lookup=json.loads(lookup_raw);descriptor=lookup.get('tool',{})
        if lookup.get('schema')!='stackmap.agent-static-packs.v1' or lookup.get('api_kind')!='read_only_static_agent_tool_lookup' or not isinstance(lookup.get('snapshot'),dict) or descriptor.get('tool_id')!=tool_id or descriptor.get('href')!='tools/'+tool_id+'.json' or not re.fullmatch(r'[0-9a-f]{64}',str(descriptor.get('sha256'))) or not isinstance(descriptor.get('bytes'),int) or isinstance(descriptor.get('bytes'),bool) or descriptor['bytes']<0:raise SystemExit('Malformed selective lookup: '+tool_id)
        if snapshot is None:snapshot=lookup.get('snapshot')
        if lookup.get('snapshot')!=snapshot:raise SystemExit('Mixed snapshots')
        raw=download(urljoin(base,descriptor['href']))
        if len(raw)!=descriptor['bytes'] or hashlib.sha256(raw).hexdigest()!=descriptor['sha256']:raise SystemExit('Snapshot changed or pack hash mismatch: '+tool_id)
        pack=json.loads(raw)
        if pack.get('schema')!='stackmap.agent-static-packs.v1' or pack.get('snapshot')!=snapshot or pack.get('tool',{}).get('tool_id')!=tool_id:raise SystemExit('Invalid selective pack identity: '+tool_id)
        packs.append(pack)
    def matches(pack):
        tool=pack['tool']
        return (not a.name or a.name.casefold() in (tool.get('name','')+' '+tool.get('short_description','')).casefold()) and (not a.category or a.category in tool.get('capability_slugs',[]) or tool.get('primary_capability_slug')==a.category)
    packs=[pack for pack in packs if matches(pack)];ids={pack['tool']['tool_id'] for pack in packs}
    result={'schema':'stackmap.agent-named-tools.v1','snapshot':snapshot,'tools':[pack['tool'] for pack in packs],'packs':packs,'query_execution':'client_side_selective_named_tool_packs','accounting':accounting,'limits':['Operational plan limits are source-bound documentary quotas, not entitlement or runtime proof.','Directed edges are catalog records, not configured or tested integrations.']}
    if a.function:
        rows=[row for pack in packs for row in pack.get('active_findings',[]) if row.get('key')==a.function and (not a.category or row.get('capability_slug')==a.category)]
        result['assertions']=rows;result['tools_with_no_matching_assertion']=sorted(ids-{row['tool_id'] for row in rows})
    if a.integrations:
        by_edge={}
        for edge in (edge for pack in packs for edge in pack.get('incident_directed_edges',[]) if edge.get('source_tool_id') in ids or edge.get('target_tool_id') in ids):
            key=edge.get('edge_id') if isinstance(edge,dict) and isinstance(edge.get('edge_id'),str) else json.dumps(edge,sort_keys=True,ensure_ascii=False)
            if key in by_edge and by_edge[key]!=edge:raise SystemExit('Conflicting duplicate integration edge: '+key)
            by_edge[key]=edge
        result['integrations']=list(by_edge.values())
    return result
result=selective(a.tool) if a.tool and not a.bulk else None
if result is None:result=legacy()
print(json.dumps(result,indent=2,ensure_ascii=False))
