from PIL import Image
import os, json

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

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

# For each counting question, approximate object count by:
# 1. Convert to grayscale
# 2. Threshold to separate foreground from background
# 3. Count connected components of reasonable size

def estimate_count(img):
    """Estimate object count by connected component analysis"""
    if img.mode == 'RGBA':
        img = img.convert('RGB')

    gray = img.convert('L')
    # Get dominant background color (assume it's near white)
    pixels = list(gray.getdata())
    # Count pixels near white (240+)
    white_px = sum(1 for p in pixels if p > 240)
    total = len(pixels)

    # If mostly white, objects are darker
    if white_px / total > 0.5:
        # Threshold at various levels to find objects
        # Simple approach: count pixels that are significantly non-white
        objects_px = sum(1 for p in pixels if p < 200)
        # Assume each object takes roughly similar area
        # Rough estimate based on typical P1 icon sizes
        avg_obj_size = total * 0.02  # ~2% of image per object
        if avg_obj_size > 0 and objects_px > 0:
            est = round(objects_px / avg_obj_size)
            return est, objects_px, total, white_px/total
    return None, 0, total, white_px/total if total > 0 else 0

# Try a more targeted approach: look for specific colored regions (non-white)
def count_colored_regions(img):
    """Detect distinct colored regions that could be objects"""
    if img.mode == 'RGBA':
        arr = list(img.getdata())
        # Filter transparent
        opaque_pixels = [(r, g, b) for r, g, b, a in arr if a > 128]
    else:
        opaque_pixels = list(img.getdata())

    if len(opaque_pixels) == 0:
        return 0, 0

    # Count non-white pixels
    non_white = sum(1 for p in opaque_pixels if (p[0] < 230 or p[1] < 230 or p[2] < 230))
    total = len(opaque_pixels)

    # For counting objects, typical P1 images have objects occupying 10-40% of image
    ratio = non_white / total if total > 0 else 0
    return non_white, total, ratio

counting_entries = [(i, data[i]) for i in range(64) if data[i]['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)

    expected = entry['answers'][0]

    if not os.path.exists(fpath):
        print(f"[{idx}] id={entry['id']}: FILE NOT FOUND - {base}")
        continue

    sz = os.path.getsize(fpath)
    if sz < 2000:
        print(f"[{idx}] id={entry['id']}: BROKEN IMAGE ({sz}B) - {base}")
        continue

    try:
        img = Image.open(fpath)
        w, h = img.size
        non_white, total, ratio = count_colored_regions(img)
        print(f"[{idx}] id={entry['id']:3d}: ans={expected:>3s}  img={w}x{h}  nonwhite={non_white/total*100:.1f}%  ({base})")
    except Exception as e:
        print(f"[{idx}] id={entry['id']}: ERROR - {e}")
