#!/usr/bin/env python3
"""Fix the coordinated-inquiry NOTICE footer bug (same defect as the letters),
then rebuild the per-recipient (letter + notice) set and the coordinated master package."""
from pathlib import Path
import subprocess, fitz

OUT = Path('/Users/icloudabe/GLAS_Rosenwald_Deep_Dive/JOINT_INQUIRY_PACKAGE/ENTITY_LETTERS_AVOWAL')
PDFDIR = OUT / 'pdf'
WITHNOTICE = OUT / 'pdf_with_notice'
CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
DISC_FONT = '/Users/icloudabe/aria/avowal_brand/fonts/DMMono-Regular.ttf'
DISCLAIMER = ('This letter was prepared by a self-represented party using the ELARIA Document Engine. '
              'AVOWAL is a technology platform, not a law firm; ELARIA is an AI operations agent, not legal counsel; '
              'neither provides legal advice. Use of AVOWAL does not create an attorney-client relationship.')

def draw_overlay(pdf_path):
    """Same overlay as the letters: full-bleed cyan/gold spine + disclaimer drawn into the reserved bottom margin."""
    doc = fitz.open(str(pdf_path))
    for page in doc:
        h = page.rect.height; w = page.rect.width
        page.draw_rect(fitz.Rect(0, 0, 5.5, h * .62), color=None, fill=(0, 212/255, 1), overlay=True)
        page.draw_rect(fitz.Rect(0, h * .62, 5.5, h), color=None, fill=(240/255, 180/255, 41/255), overlay=True)
        dl_left, dl_right = 62.0, w - 52.0
        page.draw_line(fitz.Point(dl_left, h - 66), fitz.Point(dl_right, h - 66), color=(0.02, 0.04, 0.10), width=0.6)
        page.insert_textbox(fitz.Rect(dl_left, h - 61, dl_right, h - 31), DISCLAIMER,
                            fontfile=DISC_FONT, fontname='dmmono', fontsize=5.7, color=(0.32, 0.38, 0.48), lineheight=1.3)
        page.insert_textbox(fitz.Rect(dl_left, h - 30, dl_right, h - 20), 'avowal.ai',
                            fontfile=DISC_FONT, fontname='dmmono', fontsize=5.7, color=(0.0, 0.537, 0.658))
    tmp = pdf_path.with_suffix('.ov.pdf')
    doc.save(str(tmp), garbage=4, deflate=True); doc.close(); tmp.replace(pdf_path)

# 1) Fix the notice HTML (remove the broken fixed footer) and re-render.
NHTML = OUT / 'NOTICE_OF_COORDINATED_INQUIRIES_AND_EVIDENCE_PRESERVATION.html'
NPDF  = OUT / 'NOTICE_OF_COORDINATED_INQUIRIES_AND_EVIDENCE_PRESERVATION.pdf'
html = NHTML.read_text()
# strip the rail + pgfoot prefix that causes the mid-page collision
import re
html = re.sub(r'<div class="rail"></div><div class="pgfoot">.*?</div>\s*(?=<header>)', '', html, count=1, flags=re.S)
# add the wet signature above the typed name (consistency with the entity letters), once
SIG = '<img class="wetsig" src="file:///Users/icloudabe/law_firm_associations/abe_signature.png"/>'
if 'wetsig" src=' not in html:
    html = html.replace('<p>Respectfully,</p>', f'<p>Respectfully,</p>{SIG}', 1)
NHTML.write_text(html)
cp = subprocess.run([CHROME, '--headless', '--disable-gpu', '--no-pdf-header-footer',
                     f'--print-to-pdf={NPDF}', f'file://{NHTML}'], capture_output=True, text=True)
if cp.returncode != 0 or not NPDF.exists():
    raise SystemExit(f'Chrome failed on notice: {cp.stderr}')
draw_overlay(NPDF)
print('notice rebuilt:', NPDF.name, '-', fitz.open(str(NPDF)).page_count, 'pages')

# 2) Rebuild pdf_with_notice/: each fixed letter followed by the fixed notice.
WITHNOTICE.mkdir(exist_ok=True)
letters = sorted(p for p in PDFDIR.glob('[0-9]*.pdf'))
for lp in letters:
    m = fitz.open(); m.insert_pdf(fitz.open(str(lp))); m.insert_pdf(fitz.open(str(NPDF)))
    m.save(str(WITHNOTICE / lp.name), garbage=4, deflate=True); m.close()
print(f'pdf_with_notice rebuilt: {len(letters)} files (letter + notice each)')

# 3) Rebuild the coordinated master package: notice + all 20 letters.
pkg = fitz.open()
pkg.insert_pdf(fitz.open(str(NPDF)))
for lp in letters:
    pkg.insert_pdf(fitz.open(str(lp)))
pkg_path = OUT / 'COORDINATED_INQUIRY_MASTER_PACKAGE.pdf'
pkg.save(str(pkg_path), garbage=4, deflate=True)
print(f'coordinated master package rebuilt: {pkg.page_count} pages (notice + {len(letters)} letters)')
pkg.close()
