"""Read-only service/configuration checks after approved sidecar deployment."""
import hashlib,json,pathlib,subprocess,urllib.request
root=pathlib.Path('/var/www/html/ro-th-online')
release=json.loads((root/'deploy/voice-rtc-20261001/release.json').read_text())
assert hashlib.sha256((root/'voice-rtc/voice-rtc-gateway').read_bytes()).hexdigest()==release['binarySha256']
assert (root/'voice-rtc/THIRD_PARTY_NOTICES.txt').is_file()
assert subprocess.check_output(['systemctl','is-active','ro-th-online-voice-rtc'],text=True).strip()=='active'
assert subprocess.check_output(['systemctl','is-enabled','ro-th-online-voice-rtc'],text=True).strip()=='enabled'
for name,expected in release['gameServicePidsUnchanged'].items():
    assert subprocess.check_output(['pgrep','-x',name],text=True).strip().splitlines()==expected,name+' PIDs changed'
original=(root/'deploy/voice-rtc-20261001/apache-before.conf').read_text()
current=pathlib.Path('/etc/apache2/sites-enabled/zz-ro-th-download-ssl.conf').read_text()
route='''    # WebRTC signaling only; voice audio uses DTLS/SCTP/UDP 7012.
    ProxyPass /bridge/voice-rtc ws://127.0.0.1:8090/bridge/voice-rtc retry=0
    ProxyPassReverse /bridge/voice-rtc ws://127.0.0.1:8090/bridge/voice-rtc
'''
assert current.count(route)==1 and current.replace(route,'')==original,'Apache edits exceeded new RTC route'
assert urllib.request.urlopen('http://127.0.0.1:8090/health',timeout=3).read()==b'voice-rtc-v1\n'
udp=subprocess.check_output(['ss','-Hlun','sport = :7012'],text=True).strip()
assert udp,'UDP mux not listening'
firewall=[line for line in subprocess.check_output(['ufw','status'],text=True).splitlines() if '7012/udp' in line]
assert firewall and all('ALLOW' in line for line in firewall),'UDP firewall rule missing'
print(json.dumps(dict(serviceActive=True,serviceEnabled=True,gameServicePidsUnchanged=release['gameServicePidsUnchanged'],apacheOnlyNewRoute=True,localHealth=True,udpListener=udp,udpFirewall=firewall,binarySha256=release['binarySha256']),indent=2))
