#!/usr/bin/env python3
"""
Read and extract text from PDF files.
Usage: read-pdf.py <path> [--pages N] [--summary]
"""

import sys
import argparse
import fitz  # PyMuPDF


def extract_text(pdf_path: str, max_pages: int = None) -> dict:
    """Extract text from PDF, return structured result."""
    doc = fitz.open(pdf_path)
    
    result = {
        "path": pdf_path,
        "total_pages": len(doc),
        "pages": [],
        "metadata": dict(doc.metadata) if doc.metadata else {},
    }
    
    pages_to_read = min(len(doc), max_pages) if max_pages else len(doc)
    
    for i in range(pages_to_read):
        page = doc[i]
        text = page.get_text("text").strip()
        result["pages"].append({
            "page": i + 1,
            "text": text,
            "char_count": len(text),
        })
    
    doc.close()
    return result


def format_output(result: dict, summary_only: bool = False) -> str:
    """Format extraction result for display."""
    lines = []
    
    # Header
    lines.append(f"📄 **PDF: {result['path']}**")
    lines.append(f"Pages: {result['total_pages']}")
    
    if result["metadata"].get("title"):
        lines.append(f"Title: {result['metadata']['title']}")
    if result["metadata"].get("author"):
        lines.append(f"Author: {result['metadata']['author']}")
    
    lines.append("")
    
    if summary_only:
        total_chars = sum(p["char_count"] for p in result["pages"])
        lines.append(f"Total characters: {total_chars:,}")
        preview = result["pages"][0]["text"][:500] if result["pages"] else ""
        if preview:
            lines.append(f"\n**First page preview:**\n{preview}...")
    else:
        for page in result["pages"]:
            lines.append(f"--- Page {page['page']} ---")
            lines.append(page["text"] if page["text"] else "(No text content)")
            lines.append("")
    
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="Extract text from PDF files")
    parser.add_argument("path", help="Path to PDF file")
    parser.add_argument("--pages", type=int, help="Max pages to read")
    parser.add_argument("--summary", action="store_true", help="Show summary only")
    parser.add_argument("--json", action="store_true", help="Output as JSON")
    
    args = parser.parse_args()
    
    try:
        result = extract_text(args.path, args.pages)
        
        if args.json:
            import json
            print(json.dumps(result, indent=2))
        else:
            print(format_output(result, args.summary))
            
    except Exception as e:
        print(f"Error reading PDF: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
