"""
PDF text extraction and Gemini summarization.
"""

from pathlib import Path
from typing import Optional

try:
    import fitz  # PyMuPDF
except ImportError:
    fitz = None

try:
    from google import genai
    from google.genai import types
except ImportError:
    genai = None
    types = None


SUMMARY_PROMPT = """You are an expert at creating comprehensive study notes. 
Analyze the following content from a lecture/course material and create a detailed markdown summary.

Your summary should include:
1. **Key Concepts**: Main ideas and definitions
2. **Important Points**: Critical information to remember
3. **Formulas/Equations**: Any mathematical formulas with explanations (use LaTeX: $formula$ for inline, $$formula$$ for blocks)
4. **Examples**: Notable examples mentioned
5. **Connections**: How topics relate to each other

Format the output as clean, well-structured markdown. Use headers, bullet points, and code blocks where appropriate.

Content to summarize:
---
{content}
---

Create a comprehensive markdown summary:"""


def extract_text_from_pdf(pdf_path: Path) -> str:
    if fitz is None:
        raise ImportError("PyMuPDF required: pip install pymupdf")
    doc = fitz.open(pdf_path)
    text = ""
    for page_num, page in enumerate(doc):
        text += f"\n\n--- Page {page_num + 1} ---\n\n"
        text += page.get_text()
    doc.close()
    return text.strip()


def summarize_with_gemini(text: str, gemini_api_key: str, model_name: str = "gemini-2.0-flash") -> Optional[str]:
    if genai is None:
        raise ImportError("google-genai required: pip install google-genai")
    
    if not text or len(text.strip()) < 100:
        return None
    
    client = genai.Client(api_key=gemini_api_key)
    
    max_chars = 100000
    if len(text) > max_chars:
        text = text[:max_chars] + "\n\n[Truncated...]"
    
    prompt = SUMMARY_PROMPT.format(content=text)
    response = client.models.generate_content(model=model_name, contents=prompt)
    return response.text


def process_pdfs_in_folder(folder: Path, gemini_api_key: str, model_name: str = "gemini-2.0-flash") -> tuple[int, int]:
    """
    Process all PDFs in a folder, extract text, and create markdown summaries.
    
    Returns:
        Tuple of (processed_count, failed_count)
    """
    if fitz is None:
        print("Error: PyMuPDF is required for PDF text extraction.")
        print("Install it with: pip install pymupdf")
        return 0, 0
    
    if genai is None:
        print("Error: google-genai is required for summarization.")
        print("Install it with: pip install google-genai")
        return 0, 0
    
    if not folder.exists():
        print(f"Error: Folder '{folder}' does not exist!")
        return 0, 0
    
    pdf_files = list(folder.rglob("*.pdf"))
    
    if not pdf_files:
        print("No PDF files found.")
        return 0, 0
    
    print(f"Found {len(pdf_files)} PDF files to process.\n")
    
    processed = 0
    failed = 0
    
    for pdf_path in pdf_files:
        # Skip if summary already exists
        summary_path = pdf_path.with_suffix(".md")
        if summary_path.exists():
            print(f"Skipping (summary exists): {pdf_path.name}")
            continue
        
        print(f"Processing: {pdf_path.name}")
        
        # Extract text
        print("  Extracting text...")
        text = extract_text_from_pdf(pdf_path)
        
        if not text:
            print("  No text extracted, skipping...")
            failed += 1
            continue
        
        # Generate summary
        print(f"  Generating summary with {model_name}...")
        summary = summarize_with_gemini(text, gemini_api_key, model_name)
        
        if summary:
            # Save summary
            with open(summary_path, "w", encoding="utf-8") as f:
                f.write(f"# Summary: {pdf_path.stem}\n\n")
                f.write(summary)
            print(f"  -> Summary saved to: {summary_path.name}")
            processed += 1
        else:
            failed += 1
    
    print(f"\n{'='*50}")
    print(f"Summarization complete!")
    print(f"  Successfully processed: {processed}")
    print(f"  Failed/Skipped: {failed}")
    print(f"{'='*50}")
    
    return processed, failed
