#!/usr/bin/env python3
"""Read-only login/TURN preflight through the backend's pinned SSH configuration."""
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 hashlib,json,subprocess
from pathlib import Path
root=Path('/www/wwwroot/app.connectlyvideochat.com')
names=['app/Http/Controllers/Api/AuthApi.php','routes/api.php','app/Models/User.php',
 'app/Http/Middleware/APIAuthorization.php','composer.lock']
hashes={name:hashlib.sha256((root/name).read_bytes()).hexdigest() for name in names}
def command(args):
 p=subprocess.run(args,capture_output=True,text=True,timeout=20)
 return {'status':p.returncode,'output':p.stdout[:12000]}
# Only OAuth audience identifiers are read back; never emit keys, tokens or the environment file.
audiences={}
for line in (root/'.env').read_text().splitlines():
 if '=' in line:
  key,value=line.split('=',1)
  if key.strip() in ['GOOGLE_SIGNIN_CLIENT_ID','GOOGLE_CLIENT_ID','GOOGLE_WEB_CLIENT_ID']:
   audiences[key.strip()]=value.strip().strip('"\'')
print(json.dumps({'hashes':hashes,'google_audiences':audiences,
 'config_cached':(root/'bootstrap/cache/config.php').exists(),
 'route_caches':[p.name for p in (root/'bootstrap/cache').glob('routes*.php')],
 'coturn':command(['sh','-c','command -v turnserver || true']),
 'listeners':command(['ss','-lntu']), 'firewall':command(['ufw','status']),
 'interfaces':command(['ip','-4','-o','addr','show']),
 '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)
data = json.loads(result.stdout)
path = ROOT / '.deploy/social-login-preflight.json'
path.write_text(json.dumps(data, indent=2) + '\n')
path.chmod(0o600)
print(json.dumps(data, indent=2))
