"""Debug trace the smart-fit behavior on a real PDF."""
import sys
sys.path.insert(0, '.')
import importlib.util
import fitz
from pathlib import Path

spec = importlib.util.spec_from_file_location('pdf_mod', 'translators/pdf_translator.py')
pdf_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pdf_mod)

original_write = pdf_mod.PDFTranslator._write_translated_block

def debug_write(self, page, block, font_path, rtl_target):
    target_size = block['font_size']
    original_rect = fitz.Rect(block['bbox'])
    page_rect = page.rect
    margin = 18
    is_heading = target_size >= 14
    if is_heading:
        expanded_h = original_rect
    else:
        expanded_h = fitz.Rect(
            max(original_rect.x0, page_rect.x0 + margin),
            original_rect.y0,
            page_rect.x1 - margin,
            original_rect.y1,
        )
    next_block_y = page_rect.y1 - margin
    max_expand_y = min(
        next_block_y - original_rect.y1,
        original_rect.height * 3.0,
    )
    expanded_v = fitz.Rect(
        expanded_h.x0,
        expanded_h.y0,
        expanded_h.x1,
        expanded_h.y1 + max_expand_y,
    )
    text = block['translated'][:40]
    is_heading_str = "HEAD" if is_heading else "BODY"
    print(f"  [{is_heading_str}] text={text!r} | orig={original_rect.width:.0f}x{original_rect.height:.0f} | exp_v={expanded_v.width:.0f}x{expanded_v.height:.0f} | size={target_size}", flush=True)
    result = original_write(self, page, block, font_path, rtl_target)
    print(f"      result: {result}", flush=True)
    return result

pdf_mod.PDFTranslator._write_translated_block = debug_write

PDFTranslator = pdf_mod.PDFTranslator
PDFTranslator().translate_file(
    Path('sample_files/test_corpus/test_pdf.pdf'),
    Path('sample_files/test_corpus/test_pdf_translated.pdf'),
    target_language='fr',
    source_language='en',
)
