#!/usr/bin/env python
"""Flag an underfull one-page resume (too much white space at the bottom).

resume-system rule: a one-page resume should fill the page. If the last line of
content sits more than MAX_BOTTOM_WHITESPACE_IN inches above the bottom edge, the
page is underfull -> either ADD SPACING (bullet/section spacing, secondaryRoleBefore)
or ADD CONTENT (restore a trimmed bullet, add a bullet, expand a side project).

Calibration: a comfortably full page ends ~0.85 in from the bottom edge (0.5 in
bottom margin + ~0.35 in). Overflow to a 2nd page is handled by the page-count
and orphan-tail checks, so this check only judges single-page PDFs.

Usage: python scripts/check_page_fill.py <rendered.pdf>
Exit: 0 = ok / not applicable, 1 = underfull, 2 = usage/parse error.
"""
import sys

from pypdf import PdfReader

MAX_BOTTOM_WHITESPACE_IN = 1.5   # flag if last line is higher than this above bottom edge
TARGET_LOW_IN = 0.5              # ideal fill band (reporting only)
TARGET_HIGH_IN = 1.1


def page_min_y(page):
    ys = []

    def visitor(text, cm, tm, font, size):
        if text and text.strip():
            y = tm[5]
            if y > 2:  # ignore (0,0) artifacts
                ys.append(y)

    page.extract_text(visitor_text=visitor)
    return min(ys) if ys else None


def main():
    if len(sys.argv) != 2:
        print(__doc__)
        return 2
    pdf = sys.argv[1]
    reader = PdfReader(pdf)
    n = len(reader.pages)
    pg = reader.pages[0]
    miny = page_min_y(pg)
    if miny is None:
        print("No text found on page 1.")
        return 2
    bottom_ws = miny / 72.0

    print(pdf)
    print(f"  pages: {n}")
    print(f"  bottom whitespace (last line -> bottom edge): {bottom_ws:.2f} in")
    print(f"  ideal fill band: {TARGET_LOW_IN:.2f}-{TARGET_HIGH_IN:.2f} in; flag if > {MAX_BOTTOM_WHITESPACE_IN:.2f} in")

    if n != 1:
        print(f"  note: {n} pages - fill check applies to one-page resumes; "
              f"fix overflow first (page-count + orphan-tail checks).")
        return 0
    if bottom_ws > MAX_BOTTOM_WHITESPACE_IN:
        print(f"\nUNDERFULL PAGE: {bottom_ws:.2f} in of white space at the bottom "
              f"(> {MAX_BOTTOM_WHITESPACE_IN:.2f} in).")
        print("Fix: ADD SPACING (bullet/section spacing, secondaryRoleBefore) OR "
              "ADD CONTENT (restore a trimmed bullet, add a bullet, expand a side project).")
        return 1
    if bottom_ws > TARGET_HIGH_IN:
        print(f"\nOK (slightly light): {bottom_ws:.2f} in bottom whitespace - acceptable, "
              f"but a touch more spacing or content would tighten the layout.")
        return 0
    print("\nOK: page is acceptably full.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
