# pyright: ignore
#!/usr/bin/env python3
"""
Command-line interface for the Docling PDF converter.
"""

import argparse
import sys
from pathlib import Path

from docling_converter import PDFConverter
from docling_converter.utils import setup_logging, suppress_library_logging
from loguru import logger


def main():
    parser = argparse.ArgumentParser(
        description="High-performance PDF to Markdown converter with optimized GPU utilization"
    )
    parser.add_argument("pdf_path", help="Path to the PDF file to convert")
    parser.add_argument(
        "--output-dir", "-o", default="output", help="Output directory for markdown files (default: output)"
    )
    parser.add_argument("--workers", "-w", type=int, default=2, help="Number of process workers (default: 2)")
    parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose logging")
    parser.add_argument(
        "--debug", "-d", action="store_true", help="Enable debug mode (saves extracted page PDFs)"
    )

    args = parser.parse_args()

    # Setup logging
    setup_logging(args.verbose)
    suppress_library_logging()

    # Validate input
    pdf_path = Path(args.pdf_path).resolve()
    if not pdf_path.exists():
        logger.error(f"PDF file not found: {pdf_path}")
        sys.exit(1)

    if not pdf_path.suffix.lower() == ".pdf":
        logger.error(f"File is not a PDF: {pdf_path}")
        sys.exit(1)

    # Initialize converter
    logger.info("Initialized Docling PDF converter")
    logger.info(f"Workers: {args.workers}")
    if args.debug:
        logger.info("Debug mode: ON (page PDFs will be saved)")

    converter = PDFConverter(output_dir=args.output_dir, max_workers=args.workers, debug_mode=args.debug)

    # Perform conversion
    results = converter.convert(pdf_path)

    # Report results
    logger.success(f"Successfully converted {results['success']} pages")
    if results["failed"] > 0:
        logger.warning(f"{results['failed']} pages failed to convert")

    # Exit with appropriate code
    sys.exit(0 if results["failed"] == 0 else 1)


if __name__ == "__main__":
    main()
