from PIL import Image
import os, json, struct

audit_dir = r'C:\allgifted\mathapi11v2\_work_barmodels\audit_r6'

# Load chunk data
with open(r'C:\allgifted\mathapi11v2\_work_barmodels\chunk_prod_image.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

def count_objects_by_color_clusters(img):
    """Try to count objects by looking at non-white, non-background color clusters"""
    if img.mode == 'RGBA':
        img = img.convert('RGB')

    img_small = img.resize((200, 200))
    img_q = img_small.quantize(colors=16)

    colors = img_q.getcolors()
    if not colors:
        return None

    colors.sort(key=lambda x: -x[0])

    total_pixels = sum(c[0] for c in colors)
    object_colors = []
    for cnt, idx in colors:
        pct = cnt / total_pixels
        if pct < 0.005:
            continue
        if pct > 0.85:
            continue
        object_colors.append((cnt, idx, pct))

    return len(object_colors), object_colors[:8]

# Check specific counting questions (type 2)
counting_entries = [(i, data[i]) for i in range(64) if data[i]['type'] == 2]

print("=== COUNTING QUESTIONS (type 2) ===")
for idx, entry in counting_entries:
    img_path = entry['question_image']
    base = img_path.split('/')[-1]
    fpath = os.path.join(audit_dir, base)

    if not os.path.exists(fpath) or os.path.getsize(fpath) < 2000:
        print(f"[{idx}] id={entry['id']}: SKIP - bad/missing file ({base}), size={os.path.getsize(fpath) if os.path.exists(fpath) else 'MISSING'}B")
        continue

    try:
        img = Image.open(fpath)
        result = count_objects_by_color_clusters(img)
        expected = entry['answers'][0]
        print(f"[{idx}] id={entry['id']}: ans={expected}, img={img.size}, mode={img.mode}, clusters={result[0] if result else 'N/A'}")
    except Exception as e:
        print(f"[{idx}] id={entry['id']}: ERROR {e}")

# Also check MCQ number bond questions
print("\n=== NUMBER BOND MCQs (type 1 with number patterns) ===")
for i in range(64):
    entry = data[i]
    if entry['type'] != 1:
        continue
    ans = entry['answers']
    ci = entry['correct_index']
    if ci is not None and ci < len(ans) and ans[ci]:
        print(f"[{i}] id={entry['id']}: correct='{ans[ci]}', options={ans}")
