"""Recompute polygon areas from SVG output, independently of drawing helpers."""
from pathlib import Path
import xml.etree.ElementTree as ET
import json,math,hashlib
root=Path(__file__).resolve().parent
NS={'s':'http://www.w3.org/2000/svg'}
def area(points):
 return abs(sum(x*y2-x2*y for (x,y),(x2,y2) in zip(points,points[1:]+points[:1])))/2
results={}
for name in ['teacher-demo','q1','q2','q3','q4','answers']:
 tree=ET.parse(root/(name+'.svg'));ps=[]
 for p in tree.findall('.//s:polygon',NS):
  points=[tuple(map(float,t.split(','))) for t in p.get('points').split()];ps.append({'area':area(points),'highlighted':p.get('fill')=='#8060b5'})
 groups=[]
 for i in range(0,len(ps),4):
  g=ps[i:i+4];total=sum(p['area'] for p in g);fractions=[p['area']/total for p in g];equal=all(math.isclose(f,.25,abs_tol=1e-9) for f in fractions);shade=sum(p['area'] for p in g if p['highlighted'])/total
  groups.append({'regions':4,'fractions':fractions,'equalQuarters':equal,'highlightedCount':sum(p['highlighted'] for p in g),'highlightedAreaFraction':shade,'oneQuarter':equal and math.isclose(shade,.25,abs_tol=1e-9)})
 results[name]=groups
expected={'teacher-demo':[True],'q1':[True,False,False],'q2':[False,True,False],'q3':[False,False,True],'q4':[True],'answers':[True,True,True,True]}
assert {k:[g['oneQuarter'] for g in v] for k,v in results.items()}==expected
receipt={'status':'PASS_GEOMETRY_AND_ANSWER_CORRESPONDENCE','scope':'SVG polygon shoelace area, four-region equality and highlighted actual area; no learner assessment validation','results':results,'answerKey':{'Q1':'A','Q2':'B','Q3':'C','Q4':'A (1/4)'},'plannedDistractors':'Unequal four-area partitions and two highlighted quarters are intentional authored options.','files':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in root.iterdir() if p.suffix in ['.svg','.png','.pdf']}}
(root/'validation-receipt.json').write_text(json.dumps(receipt,indent=2)+'\n');print(receipt['status'])
