"""Add PDF-calibrated approximate columns and embedded plan images; keep all outputs local."""
import argparse,base64,json
from pathlib import Path
import pymupdf
parser=argparse.ArgumentParser()
parser.add_argument('model_dir',type=Path)
parser.add_argument('pdf2',type=Path)
parser.add_argument('pdf3',type=Path)
a=parser.parse_args();model=json.loads((a.model_dir/'model.json').read_text());images={}
for level,pdf in [('2',a.pdf2),('3',a.pdf3)]:
    page=pymupdf.open(pdf)[0];rects=[]
    for drawing in page.get_drawings():
        r=drawing['rect'];fill=drawing.get('fill')
        if fill and max(fill)<.15 and 300<r.x0<1350 and 375<r.y0<2480 and 16<r.width<24 and 16<r.height<24 and len(drawing['items'])==6 and abs(r.width-r.height)<.2:
            rects.append(tuple(round(x,2) for x in r))
    rects=sorted(set(rects));xs=[(r[0]+r[2])/2 for r in rects];ys=[(r[1]+r[3])/2 for r in rects]
    if not rects:raise ValueError('No expected PDF column marks: input layout requires review')
    x0,x1,y0,y1=min(xs),max(xs),min(ys),max(ys)
    model[level]['columns']=[{'p':[round(.5+((r[0]+r[2])/2-x0)/(x1-x0)*31.9,3),round(.5+((r[1]+r[3])/2-y0)/(y1-y0)*72,3)],'w':(r[2]-r[0])/((x1-x0)/31.9),'d':(r[3]-r[1])/((y1-y0)/72)} for r in rects]
    model[level]['columnSource']='PDF square solid marks; affine-calibrated approximation, not structural verification'
    pix=page.get_pixmap(matrix=pymupdf.Matrix(.9,.9),clip=pymupdf.Rect(90,150,1640,2730))
    images[level]='data:image/jpeg;base64,'+base64.b64encode(pix.tobytes('jpg',jpg_quality=83)).decode()
(a.model_dir/'model.json').write_text(json.dumps(model,ensure_ascii=False,separators=(',',':')))
(a.model_dir/'plan-images.json').write_text(json.dumps(images,separators=(',',':')))
print('Prepared local model columns and plan images.')
