"""One bounded, video-only RTSP capture; never print the registered URI."""
import datetime
import hashlib
import json
import pathlib
import re
import subprocess
import time
import yaml

root = pathlib.Path('/work')
(root/'inputs').mkdir(exist_ok=True)
(root/'reports').mkdir(exist_ok=True)
raw = pathlib.Path('/source/streams_runtime.yaml').read_bytes()
rows = yaml.safe_load(raw)['added']
rows = rows.values() if isinstance(rows, dict) else rows
matches = [r for r in rows if str(r.get('camera_id', r.get('source_id'))) == '24']
assert len(matches) == 1, 'Expected exactly one camera24 registration'
spec = matches[0]
uri = spec['uri']
dest = root/'inputs/camera24_original.mp4'
assert not dest.exists(), 'Existing recording will not be overwritten'
summary = dict(camera_id=24, stream_id=spec['stream_id'],
               config_sha256=hashlib.sha256(raw).hexdigest(),
               source_sha256=hashlib.sha256(uri.encode()).hexdigest(),
               started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
               requested_seconds=180, wall_timeout_seconds=240,
               mode='tcp_video_streamcopy_no_rate_conversion')
command = ['ffmpeg','-nostdin','-hide_banner','-loglevel','error',
           '-rtsp_transport','tcp','-timeout','15000000','-i',uri,
           '-map','0:v:0','-an','-t','180','-c:v','copy',
           '-avoid_negative_ts','make_zero','-movflags','+faststart',str(dest)]
start = time.monotonic()
try:
    result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=240)
    summary['returncode'] = result.returncode
    errors = result.stderr.decode(errors='replace')
    summary['stderr'] = re.sub(r'[a-zA-Z]+://[^\s]+', '<endpoint omitted>', errors)[-3000:]
except subprocess.TimeoutExpired:
    summary['returncode'] = 'TIMEOUT'
summary['wall_seconds'] = round(time.monotonic()-start, 3)
summary['bytes'] = dest.stat().st_size if dest.exists() else 0
(root/'reports/capture.json').write_text(json.dumps(summary, indent=2))
print(json.dumps(summary))
raise SystemExit(0 if summary['returncode'] == 0 else 1)
