from probe import *
import shutil

ROOT=R
plan=json.loads((R/'plan.json').read_text())
if len(sys.argv)>1 and sys.argv[1]=='fixed':
    R=R/'fixed'
    R.mkdir(mode=0o700,exist_ok=False)
def save(name,value): (R/name).write_text(json.dumps(value,ensure_ascii=False,indent=2))
assert not (R/'diag-started.json').exists()
save('diag-started.json',dict(at=time.time(),reason='Determine shared H264 SDP status/caps at DESCRIBE, not repeat blind connection',caps=dict(sender_seconds=35,rx_seconds=12,cpu_each=1,ram_each_mib=512,logs_bytes=4*1024**2)))
state=R/'diag-registry';manager=Manager(state)
manager.register('diag503',plan['sender']['video'])
manager.configure(plan['sender']['uri'].split('://',1)[1].split(':',1)[0])
with manager.registry() as data:data['sources']['diag503']['port']=18601;manager.save(data)
from rtsp_test_manager import command
def run(args,timeout=20):
    if args[:2]==['docker','create']:
        idx=args.index('--entrypoint')
        args=args[:idx]+['-e','GST_DEBUG=rtspclient:5,rtspmedia:5','-e','GST_DEBUG_NO_COLOR=1','--mount',mount(ROOT/'diagnostic_worker.py','/opt/worker.py'),'--mount',mount(ops.REPO/'tools/rtsp_test_worker.py','/opt/rtsp_worker_original.py')]+args[idx:]
        # Replace only the original /opt/worker.py mount, keeping the diagnostic mount.
        orig=mount(ops.REPO/'tools/rtsp_test_worker.py','/opt/worker.py')
        j=args.index(orig);del args[j-1:j+1]
    return command(args,timeout)
manager.run=run
created=None
try:
    created=manager.start('diag503',max_seconds=35);save('diag-sender.json',created)
    time.sleep(3)
    cmd=['docker','run','--rm','--pull','never','--runtime','runc','--network',plan['network'],'--name','codex-ltb1021-rtsp503-diag-rx','--cpus','1','--memory','512m','--memory-swap','512m','--pids-limit','64','--cap-drop','ALL','-e','NVIDIA_VISIBLE_DEVICES=void','--entrypoint','timeout',IMAGE,'12','ffmpeg','-hide_banner','-loglevel','debug','-rtsp_transport','tcp','-i',created['uri'],'-an','-frames:v','20','-f','null','-']
    p=subprocess.run(cmd,capture_output=True,text=True,timeout=20);(R/'diag-rx.log').write_text(p.stdout+p.stderr)
    time.sleep(1)
    log=subprocess.run(['docker','logs','--tail','1500',created['container']],capture_output=True,text=True,timeout=8)
    txt=log.stdout+log.stderr;assert len(txt.encode())<4*1024**2
    (R/'diag-server.log').write_text(txt)
    save('diag-result.json',dict(returncode=p.returncode,decoded='20 frames successfully decoded' in p.stderr,errors=[l for l in txt.splitlines() if any(x in l for x in ['pre-describe','ERROR','WARN','could not','SDP'])]))
    print(json.dumps(dict(returncode=p.returncode,lines=[re.sub(r'rtsp://\S+','<private-uri>',l) for l in txt.splitlines() if any(x in l for x in ['pre-describe','ERROR','WARN','could not','SDP'])][-20:]),ensure_ascii=False))
finally:
    subprocess.run(['docker','rm','-f','codex-ltb1021-rtsp503-diag-rx'],capture_output=True,timeout=8)
    manager.stop('diag503')
    save('diag-cleanup.json',dict(remaining=len(manager.containers())))
