import argparse
import pathlib

import pdfplumber
from pypdf import PdfReader


def extract_frontmatter(pdf_path: pathlib.Path, pages: int) -> str:
    chunks: list[str] = []
    with pdfplumber.open(str(pdf_path)) as pdf:
        max_page = min(pages, len(pdf.pages))
        for index in range(max_page):
            text = pdf.pages[index].extract_text(x_tolerance=1, y_tolerance=3) or ""
            chunks.append(f"\n## Page {index + 1}\n\n{text.strip()}\n")
    return "\n".join(chunks)


def main() -> None:
    parser = argparse.ArgumentParser(description="Probe Xinje PDF manuals for page counts and frontmatter text.")
    parser.add_argument("--manual-dir", required=True, type=pathlib.Path)
    parser.add_argument("--output", required=True, type=pathlib.Path)
    parser.add_argument("--pages", type=int, default=12)
    args = parser.parse_args()

    args.output.parent.mkdir(parents=True, exist_ok=True)
    chunks: list[str] = ["# PDF Manual Probe\n"]
    for pdf_path in sorted(args.manual_dir.glob("*.pdf")):
        reader = PdfReader(str(pdf_path))
        chunks.append(f"\n# {pdf_path.name}\n")
        chunks.append(f"- Path: `{pdf_path}`")
        chunks.append(f"- Size bytes: {pdf_path.stat().st_size}")
        chunks.append(f"- PDF pages: {len(reader.pages)}")
        chunks.append(extract_frontmatter(pdf_path, args.pages))

    args.output.write_text("\n".join(chunks), encoding="utf-8")
    print(f"wrote {args.output}")


if __name__ == "__main__":
    main()
