"""Second rough pass of E–H after independent critique. Originals retained.
These remain reserve studies, not additional final or print-approved suites.
"""
import render_suites as r
import render_development as d
from PIL import Image,ImageDraw
import json,hashlib

OUT=r.ROOT/'semifinalists'/'revised';OUT.mkdir(exist_ok=True)
MORE={'E':('The Equal Families','Baskervville-Regular','#292522'),
      'F':('The Letter and Ceremony Rail','EBGaramond-Italic','#292522'),
      'G':('The Date Bands','Baskervville-Regular','#1D2F4A'),
      'H':('The Quiet Oldstyle','EBGaramond-Medium','#292522')}

def rebuild(base):
    f=r.Face(base.suite,base.kind);k=base.suite
    for op in base.ops:
        if op['type']=='text':
            o=op.copy();t=o['text']
            if f.kind=='sleeve':
                if t in ['Samir','Sana','Samir & Sana']:
                    o['size_px']+=8
                    if k=='E' and t=='Samir':o['x_px']=330
                    if k=='E' and t=='Sana':o['x_px']=760
            elif f.kind=='invitation':
                if t in ['Samir Khan','Sana Bano']:o['size_px']+=10 if k in ['E','H'] else 7
                if k=='E':
                    if 535<=o['y_px']<700:o['y_px']-=50
                    if t==r.DATECITY:o['y_px']=704
                    if t=='Nikah':o['y_px']=778
                    if t==r.CEREMONY:o['y_px']=839
                    if t==r.VENUE:o['y_px']=889
                if k=='H':
                    if t==r.DATECITY:o['y_px']=645
                    if t=='Nikah':o['y_px']=748
                    if t==r.CEREMONY:o['y_px']=820
                    if t==r.VENUE:o['y_px']=875
                if k=='F' and o['x_px']>900:
                    o['y_px']-=29 if t=='Nikah' else 50
            f.text(t,o['x_px'],o['y_px'],o['size_px'],o['font'],o['alignment'],o['tracking_em'],o['color'],o['block'],o['maximum_width_px'])
        elif op['type']=='line':f.line(op['x1'],op['y1'],op['x2'],op['y2'],op['color'],op['stroke'])
    return f

def revised_programme(k):
    if k in ['E','H']:return d.alt_programme(k)
    f=r.Face(k,'programme');cx=746
    f.text('Wedding Programme',cx,120,40,'display','center')
    if k=='F':
        ys=[193,248,304,408,463,556]
        for i,(title,dt,extra) in enumerate(r.EVENTS):
            f.text(title,563,ys[i],28,'display');f.para(dt,211,ys[i],24,317,28)
            y=ys[i]+35
            for line in extra:y=f.para(line,563,y,23,721,28)
        f.line(207,641,1287,641)
        f.text('Welcoming you',cx,667,32,'body','center');f.text(r.HOST,cx,710,24,'body','center')
        r.welcome(f,[211,487,763,1039],750,23,23)
    else:
        # Actual four date bands, with a shared visible day rail. Useful day
        # repetitions are added; each locked event string remains intact.
        bands=[(193,'1 November 2026',(0,)),(266,'2 November 2026',(1,)),
               (339,'3 November 2026',(2,3)),(471,'4 November 2026',(4,5))]
        for top,date,indices in bands:
            f.para(date,211,top,24,196,29,role='emphasis')
            for col,index in enumerate(indices):r.event(f,index,450+col*435,top,845 if len(indices)==1 else 410,28,23,27)
        for yy in [263,336,463,641]:f.line(207,yy,1287,yy)
        f.line(419,192,419,621)
        f.text('Welcoming you',cx,667,32,'body','center');f.text(r.HOST,cx,710,24,'body','center')
        r.welcome(f,[211,487,763,1039],750,23,23)
    return f

def board(k,fs):
    scale=.55;slot=round(1493*scale);h=round(1053*scale);pad=45
    b=Image.new('RGB',(3*slot+4*pad,h+250),'#EAE5DC');dr=ImageDraw.Draw(b)
    r.board_text(dr,k+' / SECOND ROUGH PASS / '+MORE[k][0],45,38,29)
    r.board_text(dr,'Critique revisions. Same core +36names; G adds useful shared-day repeats. Reserve study, not fifth final.',45,91,21)
    for j,f in enumerate(fs):
        im=Image.alpha_composite(f.bg,f.layer).convert('RGB');im=im.resize((round(im.width*scale),round(im.height*scale)),Image.Resampling.LANCZOS)
        b.paste(im,(pad+j*(slot+pad)+(slot-im.width)//2,160+(h-im.height)//2))
        r.board_text(dr,['SLEEVE','INVITATION','PROGRAMME'][j],pad+j*(slot+pad),h+183,20)
    p=OUT/(k+'-revised-three-face.png');b.save(p);return p

def main():
    receipt=[]
    for k,(name,display,ink) in MORE.items():
        r.CFG[k]=dict(name=name,thesis='Second rough pass',display=display,body='EBGaramond-Regular',emphasis='EBGaramond-Medium',ink=ink,accent=ink,art='none')
        fs=[rebuild(d.alt_sleeve(k)),rebuild(d.alt_invitation(k)),revised_programme(k)]
        checks=[]
        for i,f in enumerate(fs):checks.append(f.save(f'{k}-revised-0{i+1}-{f.kind}',folder='semifinalists/revised'))
        p=board(k,fs)
        receipt.append({'suite':k,'board':p.relative_to(r.ROOT).as_posix(),'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'checks':checks,'method':'Real fonts on unchanged stock; original first rough retained. This is a second rough, not a new final.'})
    (r.ROOT/'qa'/'reserve-revision-checks.json').write_text(json.dumps(receipt,indent=2,ensure_ascii=False),encoding='utf-8')
    print(json.dumps({'second_rough_boards':4,'errors':{row['suite']:[f['errors'] for f in row['checks']] for row in receipt},'protected_overlap':{row['suite']:[f['protected_overlap_pixels'] for f in row['checks']] for row in receipt}},indent=2))
if __name__=='__main__':main()
