"""Read-only Round 2 production discovery through the pinned SSH client."""
import importlib.util
import json
from pathlib import Path
import subprocess

ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('deployment_client', ROOT / 'scripts/deploy.py')
client = importlib.util.module_from_spec(spec)
spec.loader.exec_module(client)
config = client.configuration(ROOT / '.deploy/config.json')
code = r'''
import json, subprocess, socket
from pathlib import Path
root=Path('/www/wwwroot/connectlyvideochat.com/Videocall')
php=Path('/www/wwwroot/app.connectlyvideochat.com')
files={}
for folder in ['controllers','services','utils','routes','middlewares']:
 for p in (root/folder).rglob('*.js'):
  files[str(p.relative_to(root))]=p.read_text()
for name in ['server.js','db.js','signaling.js','matchmaker.js','userManager.js','package.json','package-lock.json']:
 files[name]=(root/name).read_text()
phpfiles={}
for name in ['app/Http/Controllers/Api/AuthApi.php','routes/api.php','routes/web.php','app/Models/User.php']:
 p=php/name
 if p.exists(): phpfiles[name]=p.read_text()
def command(args):
 r=subprocess.run(args,capture_output=True,text=True)
 return {'status':r.returncode,'output':r.stdout[:15000],'error':r.stderr[:1000]}
print(json.dumps({'node_files':files,'php_files':phpfiles,
 'backup_sizes':{p.name:p.stat().st_size for p in Path('/www/backup/bondvia-deploy/backups/b2351e7b71a4c78ea0b83ca43f2f8689963f2594').glob('*') if p.is_file()},
 'listeners':command(['ss','-lntu']), 'coturn':command(['sh','-c','command -v turnserver || true']),
 'os':Path('/etc/os-release').read_text(),
 'turn_dns':command(['getent','ahostsv4','turn.connectlyvideochat.com']),
 'firewall':command(['sh','-c','ufw status; iptables -S INPUT']),
 'certificates': {str(p):p.is_file() for p in [Path('/www/server/panel/vhost/cert/connectlyvideochat.com/fullchain.pem'),Path('/www/server/panel/vhost/cert/connectlyvideochat.com/privkey.pem')]},
 'main_dns':command(['getent','ahostsv4','connectlyvideochat.com']),
 'coturn_package':command(['apt-cache','policy','coturn']),
 'health':command(['curl','-fsS','http://127.0.0.1:3000/health'])}))
'''
result = subprocess.run(['ssh', '-p', str(config['port']), *client.ssh_options(config),
                         f"{config['user']}@{config['host']}", 'python3 -'], input=code,
                        text=True, capture_output=True, check=True)
path = ROOT / '.deploy/round2-inspection.json'
path.write_text(result.stdout)
path.chmod(0o600)
data=json.loads(result.stdout)
for key in ['backup_sizes','listeners','coturn','os','turn_dns','main_dns','firewall','certificates','coturn_package','health']:
 print(key, data[key])
print('Source snapshot saved privately; no environment secrets read.')
