"""Operate the scoped production TURN setup through pinned SSH."""
import argparse
import base64
import importlib.util
import json
from pathlib import Path
import subprocess

from turn_proof import validate

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)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['setup', 'credentials', 'activate'])
parser.add_argument('--production', action='store_true')
args = parser.parse_args()
if not args.production:
    raise ValueError('Explicit production scope required')
config = client.configuration(ROOT / '.deploy/config.json')
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
if subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT, text=True).strip():
    raise ValueError('TURN operations require clean reviewed committed source')
payload = {'action': args.action, 'tooling_release': revision}
if args.action == 'activate':
    proof = json.loads((ROOT / '.deploy/round2-relay-proof.json').read_text())
    validate(proof)
    payload['probe'] = proof
encoded = base64.b64encode(json.dumps(payload).encode()).decode()
result = subprocess.run(['ssh', '-p', str(config['port']), *client.ssh_options(config),
                         f"{config['user']}@{config['host']}", 'python3 - ' + encoded],
                        input=(ROOT / 'scripts/turn_proof.py').read_text() + '\n' +
                        (ROOT / 'scripts/round2-turn-remote.py').read_text(), text=True, capture_output=True)
if result.returncode:
    print(result.stderr)
    raise SystemExit(result.returncode)
if args.action == 'credentials':
    path = ROOT / '.deploy/round2-probe-credentials.json'
    path.write_text(result.stdout)
    path.chmod(0o600)
    print('Temporary probe credentials saved privately; values omitted')
else:
    print(result.stdout)
