"""Extract text from digital/text-based PDFs using pymupdf."""

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import fitz  # pymupdf

from output_utils import output_to_file_or_stdout


def extract(pdf_path: str) -> list[dict]:
    """Return list of {"page": int, "text": str} for each page."""
    results = []
    with fitz.open(pdf_path) as doc:
        for i, page in enumerate(doc, start=1):
            text = page.get_text("text")
            results.append({"page": i, "text": text})
    return results


def main():
    parser = argparse.ArgumentParser(description="Extract text from digital PDFs")
    parser.add_argument("pdf", help="Path to input PDF")
    parser.add_argument("output", nargs="?", default=None, help="Output file path")
    parser.add_argument("--format", choices=["txt", "json", "md"], default="txt",
                        dest="fmt", help="Output format (default: txt)")
    args = parser.parse_args()

    pages = extract(args.pdf)

    if args.fmt == "json":
        data = {"extractor": "native", "pages": pages}
    else:
        data = pages

    output_to_file_or_stdout(data, args.fmt, args.output)


if __name__ == "__main__":
    main()
