#!/usr/bin/env python3
"""Read-only control for the real-app Pi server-discovery reproduction."""
import argparse, datetime, json, pathlib, re, subprocess
p=argparse.ArgumentParser();p.add_argument('--thread',required=True);p.add_argument('--port',default='8799');a=p.parse_args()
listeners=subprocess.check_output(['ss','-H','-ltnp','sport = :'+a.port],text=True)
rows=[]
for pid in re.findall(r'pid=(\d+)',listeners):
    env=pathlib.Path('/proc/'+pid+'/environ').read_bytes().split(b'\0')
    thread=next((v.decode().split('=',1)[1] for v in env if v.startswith(b'T3CODE_THREAD_ID=')),None)
    rows.append({'pid':int(pid),'threadMatches':thread==a.thread,'command':pathlib.Path('/proc/'+pid+'/comm').read_text().strip()})
print(json.dumps({'utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'port':int(a.port),'listeners':rows},indent=2))
