import json
import random
import os

# ── A. 환경 설정 ────────────────────────────────────────────────
DATA_ROOT = '/data/ltb/ultralytics/objects365_mmyolo_coco'
VAL_JSON  = os.path.join(DATA_ROOT, 'val_coco.json')
IMG_DIR   = os.path.join(DATA_ROOT, 'images')

# ── B. JSON 로드 ───────────────────────────────────────────────
if not os.path.exists(VAL_JSON):
    raise FileNotFoundError(f"Annotation file not found: {VAL_JSON}")
with open(VAL_JSON, 'r') as f:
    coco = json.load(f)

images = coco.get('images', [])
n_check = min(200, len(images))
sampled = random.sample(images, n_check)

# ── C. 파일 존재 여부 확인 ─────────────────────────────────────
results = []
for entry in sampled:
    fname = entry['file_name']
    # JSON 에 file_name 만 있을 때
    # 실제 경로는 DATA_ROOT/images/<file_name>
    full_path = os.path.join(IMG_DIR, fname)
    exists = os.path.isfile(full_path)
    results.append((fname, full_path, exists))

# ── D. 결과 출력 ────────────────────────────────────────────────
exists_cnt = sum(1 for _,_,e in results if e)
miss_cnt   = n_check - exists_cnt

print(f"샘플 {n_check}개 중 {exists_cnt}개 파일이 존재합니다. ({miss_cnt}개 누락)\\n")
print("누락된 파일 리스트 (최대 20개):")
for fname, path, exists in results:
    if not exists:
        print("  -", fname)
        if miss_cnt > 20 and results.index((fname,path,exists)) >= 19:
            print("  ...")
            break
