import ast
import json
import os
from pathlib import Path
import subprocess

os.umask(0o077)
root = Path(__file__).parent
repo = Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
runner = '/root/.local/bin/codex-git-closeout'
old_path = Path('/tmp/codex/ltb1021/2026-09-14_contextra-rtsp-shared_r01/manifest.json')
old = json.loads(old_path.read_text())
job = 'contextra-rtsp-shared-20260914-165217-r02'

def run(args):
    return subprocess.check_output(args, text=True, timeout=45)

assert run(['git','-C',str(repo),'rev-parse','HEAD']).strip() == 'c2ceb05277dca15292cc25caf9efe93d39f0ee50'
assert not run(['git','-C',str(repo),'diff','--cached','--name-only']).strip()
paths = sorted(set(run(['git','-C',str(repo),'diff','--name-only']).splitlines() +
                   run(['git','-C',str(repo),'ls-files','--others','--exclude-standard']).splitlines()))
assert paths == sorted(item['path'] for item in old['paths'])
run(['git','-C',str(repo),'diff','--check'])
for path in paths:
    if path.endswith('.py'):
        ast.parse((repo/path).read_text())
args = [runner,'prepare','--repository',str(repo),'--output',str(root/'manifest.json'),
        '--job-id',job,'--profile','ltb1021','--session-alias','work-session',
        '--title','feat(rtsp-test): 공통 URI와 공유 송출 Anchor 및 Swagger source 준비',
        '--verify','24 source tests previously PASS; installed host Gst1.24.2 RTP/RTCP callbacks PASS; current AST/diff PASS; actual shared/LAN/SR wire NOT_RUN; API registration2 tests WAIT; no operating mutation']
for path in paths:
    args += ['--path',path]
for message in [
    'Why=동일 URI로 AI와 Web이 현재 영상과 공통 시간 기준을 공유하는 반복 시험을 준비한다.',
    'What=LAN bind와 실행별 URI/Anchor 조회, 내부 keeper와 public shared media key, RTCP SR 계산, Swagger canonical identity 전달 및 중복 source 차단을 준비했다.',
    'Impact=source 준비 단계이며 실제 shared/LAN 송수신은 미검증이다. sample01 교체는 승인만 확보했고 registry/운영 image/AI/Redis는 변경하지 않았다.',
    'Verify=표적24 tests와 host 공식 RTP/RTCP parser callback PASS. 이번에는 파일과 hash/AST/diff만 재확인했다. API registration2 tests와 실제 송수신 및 image 반영은 대기다.',
    'Rollback=운영 반영 전 source 변경만 되돌릴 수 있다. 후속 반영 시 이전 registry/owned sender 조건을 먼저 확인하고 기존 영상과 모델을 보존한다.'
]:
    args += ['--message',message]
prepared = json.loads(run(args))
batch = json.loads(run([runner,'batch-prepare','--output',str(root/'git-batch.json'),
    '--batch-id',job,'--profile','ltb1021','--session-alias','work-session','--expected-group-count','1',
    '--repository-label','contextra','--manifest',str(root/'manifest.json'),
    '--expect-plan-hash',prepared['plan_hash']]))
print(json.dumps(batch))
