#!/usr/bin/env python3
"""
PDF repair script using PyMuPDF.

Repairs malformed PDF coordinates and other structural issues that can cause
parsing errors in docling and other PDF processing libraries.
"""

import sys
from pathlib import Path

import pymupdf


def repair_pdf(input_path: str, output_path: str | None = None) -> None:
    """
    Repair a PDF by re-saving it through PyMuPDF.

    This process:
    - Fixes malformed bounding boxes
    - Normalizes coordinate systems
    - Repairs structural issues
    - Optimizes the PDF structure

    Args:
        input_path: Path to the input PDF
        output_path: Path for repaired PDF (defaults to input_repaired.pdf)
    """
    input_pdf = Path(input_path)

    if not input_pdf.exists():
        print(f"Error: File not found: {input_path}")
        sys.exit(1)

    if output_path is None:
        output_path = input_pdf.parent / f"{input_pdf.stem}_repaired.pdf"

    print(f"Repairing: {input_pdf}")
    print(f"Output: {output_path}")

    try:
        # Open and re-save the PDF (this repairs structural issues)
        doc = pymupdf.open(input_pdf)

        print(f"  Pages: {doc.page_count}")
        print(f"  Metadata: {doc.metadata.get('title', 'Unknown')}")

        # Save with garbage collection and compression
        doc.save(
            output_path,
            garbage=4,  # Maximum garbage collection
            deflate=True,  # Compress streams
            clean=True,  # Clean up page structure
        )

        doc.close()

        print("✓ PDF repaired successfully")
        print(f"  Original size: {input_pdf.stat().st_size:,} bytes")
        print(f"  Repaired size: {Path(output_path).stat().st_size:,} bytes")

    except Exception as e:
        print(f"✗ Error repairing PDF: {e}")
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: repair_pdf.py <input.pdf> [output.pdf]")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None

    repair_pdf(input_file, output_file)
