import pathlib
import sys

import pdfplumber


def main() -> None:
    if len(sys.argv) != 5:
        raise SystemExit("usage: extract_pdf_pages.py <pdf-path> <start-page> <end-page> <output-md>")
    pdf_path = pathlib.Path(sys.argv[1])
    start = int(sys.argv[2])
    end = int(sys.argv[3])
    output = pathlib.Path(sys.argv[4])
    output.parent.mkdir(parents=True, exist_ok=True)

    chunks = [f"# Extracted PDF Pages\n\nSource: `{pdf_path}`\n\nPages: {start}-{end}\n"]
    with pdfplumber.open(str(pdf_path)) as pdf:
        for page_number in range(start, end + 1):
            page = pdf.pages[page_number - 1]
            text = page.extract_text(x_tolerance=1, y_tolerance=3) or ""
            chunks.append(f"\n\n## PDF Page {page_number}\n\n{text.strip()}\n")
    output.write_text("\n".join(chunks), encoding="utf-8")
    print(f"wrote {output}")


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