from common import *
import csv
import re
import sys
sys.path.insert(0,str(REPO/'tools'))
from rtsp_test_manager import Manager
from rtsp_test_prepare import file_hash, prepare_h264
live=json.loads((R/'live.json').read_text());frames=json.loads((R/'frames.json').read_text());prepared=json.loads((R/'prepared.json').read_text())
assert file_hash(prepared['source'])==prepared['source_sha256']
assert file_hash(prepared['output'])==prepared['output_sha256']
reused=prepare_h264(prepared['source'],str(Path(prepared['output']).parent));assert reused['reused']
for path in (Path(prepared['output']),Path(prepared['output']).with_suffix('.json'),Path(prepared['output']).with_suffix('.lock')):
    path.chmod(0o600)
plan=json.loads((R/'plan.json').read_text());build=json.loads((R/'build.json').read_text())
assert all(g.sha(Path(p))==h for p,h in plan['model_hashes'].items())
source=json.loads((R/'source.json').read_text());assert all(g.sha(REPO/p)==h for p,h in source['hashes'].items())
current=api('/api/v1/streams/rtsp-test-01');assert current['state']=='stopped' and not current['cleanup_pending']
c=g.inspect();assert c['Image']==build['image_id'] and c['State']['Health']['Status']=='healthy'
sender=next(s for s in Manager().status() if s['name']=='sample01');assert sender['state']=='STREAMING' and sender['anchor']
old_others=plan['other_containers'];now=g.others()
assert all(now[k]==v for k,v in old_others.items() if k in now)
assert len(set(old_others)-set(now))==1 and len(set(now)-set(old_others))==1
settings=api('/api/v1/streams/rtsp-test-01/settings')['configured']
assert settings['intrusion']['enabled'] and settings['analysisFpsTarget']==10
env=dict(x.split('=',1) for x in c['Config']['Env'])
assert env['CONTEXTRA_METADATA_MAX_MESSAGE_BYTES']=='10485760' and env['CONTEXTRA_METADATA_MAX_BYTES']=='268435456'
redis_live=redis('admin','CONFIG','GET','maxmemory','maxmemory-policy')
assert redis_live['maxmemory']=='8589934592'
red=sum(o['color']=='#FF3030' for f in frames for o in f['objects'])
summary=dict(status='AI_PASS_WINDOWS_USER_CHECK_PENDING',windows=dict(cli='DLL_LOAD_FAILED_0xC0000135',potplayer='NOT_VERIFIED',original_failure_cause='NOT_CONFIRMED'),
    media=dict(codec='h264',width=1280,height=720,frames=1218,seconds=121.8,prepare_seconds=prepared['elapsed_seconds'],bytes=prepared['bytes'],reuse_verified=True),
    runtime=dict(result_fps=live['result_fps'],queue=live['queue'],redis_frame_samples=live['redis_samples'],rtp_present=live['rtp_present'],
        time_arithmetic='PASS',independent_wire_pixel_match='NOT_TESTED',redis_ack_stable_fps='NOT_SEPARATELY_MEASURED',
        events=live['events'],red_objects_in_samples=red,delivery='NOT_SUBMITTED',artifact_uri=None,cleanup_seconds=live['final']['last_cleanup']['elapsed_s']),
    limits=dict(message_bytes=10485760,queue_bytes=268435456,stream_length=30,ttl_seconds=10,redis_live_bytes=8589934592,
        redis_compose_recreate_bytes=8589934592,redis_existing_container_restart_bytes=2147483648),
    current=dict(analytics='healthy',ai='stopped',sender='continuous retained',intrusion='enabled configuration retained',model_hashes_preserved=True),
    windows_helpers='ffprobe process absent',capacity_errors=0)
save('summary.json',summary)
with (R/'summary.csv').open('w') as f:
    w=csv.writer(f);w.writerow(['boundary','result','detail'])
    w.writerows([['prepare','PASS','same dimensions duration and frame count; reusable'],['AI RTP','PASS','90 retained Redis frames with raw RTP and consistent arithmetic'],
        ['runtime','PASS',str(live['result_fps'])+' result FPS; queue0'],['Windows','WAIT','tool DLL failure; PotPlayer manual check'],
        ['Redis capacity','PARTIAL','live/recreate8GiB; existing container restart2GiB'],['cleanup','PASS','AI stopped; sender retained']])
paths=['tools/RTSP_TEST_GUIDE.ko.md','tools/RTSP_SWAGGER_GUIDE.ko.md',
       'docs/profiles/ltb1021/topics/runtime-lifecycle/runs/20260915T094924+0900-run-rtsp-compat-intrusion.md',
       'docs/profiles/ltb1021/topics/runtime-lifecycle/decision/20260915T094924+0900-decision-rtsp-compat-capacity.md']
links=0
for p in paths:
    file=REPO/p
    for target in re.findall(r'\]\(([^)]+)\)',file.read_text()):
        if target.startswith(('http:','https:','#')):continue
        assert (file.parent/target.split('#',1)[0]).resolve().exists(),target
        links+=1
subprocess.run(['git','diff','--check'],cwd=REPO,check=True)
save('docs-verify.json',dict(local_links=links,status='PASS'))
for path in R.iterdir():
    if path.is_file():path.chmod(0o600)
print(json.dumps(summary))
