import os, json, glob, re
from collections import Counter
BASE = os.path.dirname(os.path.abspath(__file__))
def slugify(s): return re.sub(r'[^a-z0-9]+','-', (s or '').lower()).strip('-')
def level_of(src):
    m = re.search(r'\bP([1-6])\b', src or '')
    return 'P'+m.group(1) if m else '?'
rows=[]
for f in glob.glob(os.path.join(BASE,'**','manifest.json'), recursive=True):
    try: m=json.load(open(f,encoding='utf-8'))
    except Exception: continue
    if not isinstance(m,dict): continue
    sp=((m.get('paper') or {}).get('source_prefix')) or ''
    slug=slugify(sp)
    for q in m.get('questions',[]):
        if q.get('image_options'):
            src=q.get('source') or (sp+' Q'+str(q.get('n')))
            nopts=sum(1 for k in ['answer0','answer1','answer2','answer3'] if q.get(k) not in (None,''))
            rows.append({'source':src,'level':level_of(src),'slug':slug,'n':q.get('n'),
                         'nopts':nopts,'image_needed':bool(q.get('image_needed'))})
json.dump(rows, open(os.path.join(BASE,'_imgopt_questions.json'),'w',encoding='utf-8'), ensure_ascii=False, indent=1)
print('image-option MCQ questions across all manifests:', len(rows))
print('by level:', dict(Counter(r['level'] for r in rows)))
