"""Public RTP read + SDK metadata copy/release; no actual Decode/inference claim."""
import ctypes
import gc
import glob
import sys
from dataclasses import asdict
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
from pyservicemaker import Buffer, Pipeline
from app.frame_ingress import FrameIngress

assert not glob.glob('/dev/nvidia*')
Gst.init(None)
from sdk_rtsp_compose_probe import verify_source_composition
verify_source_composition()
fixture = ctypes.CDLL('/fixture.so')
fixture.attach_fixture.argtypes = [ctypes.c_size_t, ctypes.c_bool, ctypes.c_bool]
fixture.copy_fixture_frames.argtypes = [ctypes.c_size_t, ctypes.c_size_t]
rtp = ctypes.CDLL(sys.argv[1])
rtp.attach_rtp_fixture.argtypes = [ctypes.c_size_t, ctypes.c_uint, ctypes.c_uint]
ingress = FrameIngress('test-server', 'test-camera', 'test-stream', 'test-run', 1,
                       clock_ns=lambda: 123456000000, frame_time_anchor={'startWallTimeMs': 1000, 'synthetic': True})
for seq, raw in enumerate((0, 90000, 2**32-1, 0)):
    buf = Gst.Buffer.new()
    assert fixture.attach_fixture(hash(buf), False, False) == 0
    assert rtp.attach_rtp_fixture(hash(buf), raw, 90000) == 0
    wrapped = Buffer(buf)
    ingress.stamp(wrapped.batch_meta)
    detached = Gst.Buffer.new()
    assert fixture.copy_fixture_frames(hash(buf), hash(detached)) == 0
    del wrapped, buf
    gc.collect()
    copied = Buffer(detached)
    frame = next(iter(copied.batch_meta.frame_items))
    value = ingress.copy(frame)
    assert value.frame_seq == seq and value.frame_time.source_rtp_timestamp == raw
    assert value.ingest_time_wall_ms == 123456
    assert value.frame_time.source_time_wall_ms == (None if seq == 3 else 1000 + raw*1000//90000)
    other = FrameIngress('test-server', 'test-camera', 'test-stream', 'new-run', 2)
    try: other.copy(frame)
    except ValueError: pass
    else: raise AssertionError('stale accepted')
    del frame, copied, detached
    gc.collect()
print('SDK_RTP_PASS: public Element/RTP/copy/release/Frame0/wrap/generation; GPU0')
