import hashlib
import json
import os
import re
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

ROOT = Path(__file__).resolve().parents[1]
os.umask(0o077)
now = datetime.now(ZoneInfo('Asia/Seoul')).isoformat(timespec='seconds')
report = ROOT / 'shared/00_COMPARISON_ko.md'
links = re.findall(r'\]\(([^)]+)\)', report.read_text())
assert all((report.parent / link).exists() for link in links if link != 'manifest.json')
comparison = json.loads((ROOT / 'shared/comparison.json').read_text())
inventory = []
for path in sorted(ROOT.rglob('*')):
    if path.is_file() and '__pycache__' not in path.parts and path.name != 'manifest.json':
        path.chmod(0o600)
        inventory.append(dict(path=str(path.relative_to(ROOT)), size_bytes=path.stat().st_size,
                              sha256=hashlib.sha256(path.read_bytes()).hexdigest()))
manifest = dict(schema_version='codex.artifact-manifest.v1', created_at=now,
    profile='ltb1021', project='contextra', task='camera24-offline-compare',
    run_id=ROOT.name, lifecycle='durable-large', cleanup_candidate_at='manual-review',
    operational_changes=[], source_and_validation=comparison['verified'], files=inventory,
    boundary='Read-only live observation and saved offline statistics; no frame-paired performance evaluation.')
(ROOT / 'shared/manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2)+'\n')
receipt_root = Path('/tmp/codex/ltb1021') / ROOT.name
receipt_root.mkdir(parents=True, exist_ok=True, mode=0o700)
receipt = dict(schema_version='ltb1021.codex_hub.report_receipt.v1',
    receipt_id='20261101-camera24-offline-compare-r01', timestamp=now, session_alias='work-session',
    task='camera24 관절0.10 실효 반영 확인과 45초 metadata/기존 오프라인 R5 비교',
    results=[
        'configured/effective 모두 사람0.25·관절0.10, R5. 설정/run/source 지문 전후 유지.',
        '45.030초452관측, 빨강 유지 포함50관측, 새 Event0. 같은 run의 이전 Event READY/SENT200 확인.',
        '오프라인201관측의 현재7/활성그룹 유지 포함31과 구분 비교. 같은 원본 Frame/PTS 대조는 불가하여 정확도 동등성은 미판정.',
        '관절 가용성 약99%로 유사하지만 미추적 비율 및 Tracker frame_rate10/30 차이 확인. 자동 튜닝 없음.',
        str(report)],
    verify=['Redis 오류0, Frame/PTS 순서 및 색상 대응 통과; 오프라인 Pose/진단 SHA256 일치.',
            '설정/서비스/Start/Stop/모델/Pose/Tracking/엔진 재실행 및 Git 변경 없음. 비저장소 evidence만 추가.',
            '전체 최근 Event SELECT timeout은 보존, 최근10분으로 제한한 읽기 조회 성공.'],
    commits=[], remaining=['동일 장면 정렬과 현재 조건/유지/재무장 상세 비교는 별도 단계.',
                           '브라우저 알람과 정오탐 성능은 사용자 피드백 필요.'])
receipt_path = receipt_root / 'receipt.json'
receipt_path.write_text(json.dumps(receipt, ensure_ascii=False, indent=2)+'\n')
receipt_path.chmod(0o600)
print(json.dumps({'files': len(inventory), 'report_links': len(links), 'receipt': str(receipt_path)}))
