#!/usr/bin/env python3
"""Generate mask for LaMa inpainting based on OCR-detected text regions"""
import argparse
import cv2
import numpy as np

def generate_mask(img_path, mask_path, template_name="m03"):
    img = cv2.imread(img_path)
    h, w = img.shape[:2]
    mask = np.zeros((h, w), np.uint8)

    # OCR-detected text boxes for m03 (from earlier analysis)
    if template_name == "m03":
        boxes = [
            [536,939,1109,968], [302,1023,557,1062], [606,1031,648,1054],
            [741,1029,863,1050], [1026,1029,1140,1050], [604,1050,648,1081],
            [741,1052,828,1081], [600,1092,664,1119], [602,1160,697,1181],
            [598,1184,784,1217], [597,1224,714,1256], [601,1289,641,1322],
            [911,1292,1033,1313], [598,1361,724,1382], [911,1359,995,1380],
            [908,1382,1275,1415], [598,1432,728,1453], [910,1428,1086,1453],
            [1006,1457,1041,1489]
        ]
    else:
        raise ValueError(f"Unknown template: {template_name}")

    # Dilate boxes by 8px
    for x1,y1,x2,y2 in boxes:
        cv2.rectangle(mask, (max(0,x1-8),max(0,y1-8)), (min(w,x2+8),min(h,y2+8)), 255, -1)

    # Protect regions
    scale_f = min(w/900, h/630)
    sf = lambda v: max(1, int(v * scale_f))
    
    protect = [
        # Photo area
        (sf(280), sf(118), sf(280)+sf(165), sf(118)+sf(200)),
        # Header decoration area (title, gold line, emblem)
        (0, 0, w, sf(100)),
        # MRZ background area
        (0, sf(360)+6*sf(28)+sf(5)+sf(60), w, sf(360)+6*sf(28)+sf(5)+sf(60)+sf(70)),
        # Borders
        (0, 0, sf(20), h),
        (w-sf(20), 0, w, h),
        (0, 0, w, sf(20)),
        (0, h-sf(20), w, h),
    ]
    for x1,y1,x2,y2 in protect:
        cv2.rectangle(mask, (x1,y1), (x2,y2), 0, -1)

    # Morphological close to connect gaps
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

    cv2.imwrite(mask_path, mask)
    print(f"✓ Mask saved: {mask_path} (white pixels: {np.sum(mask>0)})")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--img", required=True, help="Template image")
    parser.add_argument("--mask", required=True, help="Output mask path")
    parser.add_argument("--template", default="m03", help="Template name (m03)")
    args = parser.parse_args()
    generate_mask(args.img, args.mask, args.template)