"""Manual one-shot launch only, after user Start and explicit observation request."""
import argparse
import json
import os
from pathlib import Path
import stat
import subprocess

HERE=Path(__file__).parent
parser=argparse.ArgumentParser()
parser.add_argument('--selftest',action='store_true')
parser.add_argument('--observe',action='store_true')
args=parser.parse_args()
assert args.selftest != args.observe, 'Choose exactly one explicit mode'
os.umask(0o077)
request={'mode':'selftest' if args.selftest else 'observe'}
if args.observe:
    private=Path('/workspace/contextra-runtime-config/secure-bridge/login-body.json')
    info=private.lstat()
    # Existing private bridge files belong to the deployed Sidecar UID 10001.
    parent=private.parent.lstat()
    assert stat.S_ISREG(info.st_mode) and info.st_uid==10001 and info.st_mode & 0o077==0
    assert stat.S_ISDIR(parent.st_mode) and parent.st_uid==10001 and parent.st_mode & 0o077==0
    request['redis']=json.loads(private.read_text())['redis']
target=HERE/('selftest.jsonl' if args.selftest else 'observation.jsonl')
with target.open('x') as output:
    result=subprocess.run(['docker','exec','-i','contextra-analytics-1','python3','-B','-u',
                           '-c',(HERE/'worker.py').read_text()],
        input=json.dumps(request),text=True,stdout=output,stderr=subprocess.DEVNULL,
        timeout=215 if args.observe else 15)
print(json.dumps({'exit_code':result.returncode,'output':str(target),'observed':args.observe}))
raise SystemExit(result.returncode)
