"""Insert SCF electronic signature into NTR PDFs in the FOR IF's use area."""

import fitz  # PyMuPDF
import os

SIGNATURE_PATH = '/tmp/thor_scf_nov2026/SCF_signature.jpg'

# NTR files to process: (source_path, output_path)
NTR_FILES = [
    ('F_20261114', '12-9'),
    ('F_20261116', '12-7-2'),
    ('F_20261116', '15-4'),
    ('F_20261117', '10-10'),
    ('F_20261118-1', '1-11'),
    ('F_20261118-2', '5-9'),
    ('F_20261119_Guardian', '13-6'),
    ('F_20261119_Guardian', '36-14-1'),
    ('F_20261121-1', '1-1'),
    ('F_20261121-2', '37-14-4'),
    ('F_20261122', '37-14-5'),
    ('F_20261123', '16-14-2'),
    ('F_20261123', '16-14-6'),
    ('F_20261124', '10-9'),
]

def find_for_if_use_region(page):
    """Find the 'FOR IF's use' text region on a page to know where to insert signature."""
    text_dict = page.get_text("dict")
    for block in text_dict.get("blocks", []):
        for line in block.get("lines", []):
            for span in line.get("spans", []):
                text = span.get("text", "").strip()
                if "FOR IF" in text.upper():
                    bbox = span.get("bbox")
                    return bbox
    return None

def insert_signature_into_ntr(input_path, output_path, signature_path):
    """Insert signature image into NTR PDF's FOR IF's use area."""
    doc = fitz.open(input_path)
    
    # Read signature image
    sig_doc = fitz.open(signature_path)
    # Actually, insert image directly
    
    page = doc[0]  # First page
    page_rect = page.rect
    
    # Find FOR IF's use region
    for_if_bbox = find_for_if_use_region(page)
    
    if for_if_bbox:
        # Insert signature to the right of or below "FOR IF's use" text
        # Typical NTR has "FOR IF's use" label in a column, signature goes in that column below
        x0, y0, x1, y1 = for_if_bbox
        
        # Signature placement: below the "FOR IF's use" text, centered in that column
        sig_width = 100
        sig_height = 50
        sig_x0 = x0
        sig_y0 = y1 + 5  # just below the text
        sig_x1 = sig_x0 + sig_width
        sig_y1 = sig_y0 + sig_height
        
        sig_rect = fitz.Rect(sig_x0, sig_y0, sig_x1, sig_y1)
    else:
        # Fallback: insert at standard NTR position (bottom right area)
        # Based on page analysis, FOR IF's use is typically at bottom
        page_width = page_rect.width
        page_height = page_rect.height
        
        # Place signature in bottom right quadrant
        sig_rect = fitz.Rect(
            page_width * 0.65,  # 65% from left
            page_height * 0.75,  # 75% from top
            page_width * 0.95,  # 95% from left
            page_height * 0.90,  # 90% from top
        )
    
    # Insert the signature image
    page.insert_image(sig_rect, filename=signature_path)
    
    doc.save(output_path)
    doc.close()
    print(f"  Signature inserted: {os.path.basename(output_path)}")
    if for_if_bbox:
        print(f"    Found 'FOR IF's use' at bbox: {for_if_bbox}")
    else:
        print(f"    Used fallback position")

# Process all NTRs
base_dir = '/tmp/thor_scf_nov2026/extracted'
output_dir = '/tmp/thor_scf_nov2026/signed_ntrs'
os.makedirs(output_dir, exist_ok=True)

for zip_folder, ntr_id in NTR_FILES:
    input_file = f'{base_dir}/{zip_folder}/{ntr_id}NTR.pdf'
    output_file = f'{output_dir}/{ntr_id}NTR_IFS SIGNED.pdf'
    
    if os.path.exists(input_file):
        try:
            insert_signature_into_ntr(input_file, output_file, SIGNATURE_PATH)
        except Exception as e:
            print(f"  ERROR for {ntr_id}: {e}")
    else:
        print(f"  NOT FOUND: {input_file}")

print(f"\nAll NTR signatures processed. Output dir: {output_dir}")
print(f"Files: {os.listdir(output_dir)}")
