import pathlib
import re
import sys

from pypdf import PdfReader


def compact(text: str) -> str:
    return re.sub(r"\s+", " ", text or "").strip()


def main() -> None:
    if len(sys.argv) < 3:
        raise SystemExit("usage: search_pdf_keywords.py <pdf-path> <keyword> [keyword...]")
    pdf_path = pathlib.Path(sys.argv[1])
    keywords = sys.argv[2:]
    reader = PdfReader(str(pdf_path))
    print(f"PDF: {pdf_path}")
    print(f"PAGES: {len(reader.pages)}")
    for page_index, page in enumerate(reader.pages, start=1):
        text = compact(page.extract_text() or "")
        if not text:
            continue
        for keyword in keywords:
            if keyword in text:
                pos = text.find(keyword)
                start = max(0, pos - 160)
                end = min(len(text), pos + len(keyword) + 260)
                print(f"\nPAGE {page_index} KEYWORD {keyword}")
                print(text[start:end])


if __name__ == "__main__":
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")
    main()
