"""
Core functionality for PDF page counting.
"""

import os
import PyPDF2
from datetime import datetime
from typing import List, Tuple, Union


def count_pdf_pages(pdf_path: str) -> int:
    """
    Count the number of pages in a PDF file.

    Args:
        pdf_path (str): Path to the PDF file

    Returns:
        int: Number of pages, or -1 if error occurred

    Raises:
        FileNotFoundError: If the PDF file doesn't exist
        Exception: If the PDF file is corrupted or unreadable
    """
    if not os.path.exists(pdf_path):
        raise FileNotFoundError(f"PDF file not found: {pdf_path}")

    try:
        with open(pdf_path, "rb") as file:
            pdf_reader = PyPDF2.PdfReader(file)
            return len(pdf_reader.pages)
    except Exception as e:
        print(f"Error reading {pdf_path}: {e}")
        return -1


def generate_markdown_report(
    results: List[Tuple[str, Union[int, str]]], total_pages: int
) -> str:
    """
    Generate markdown content for the report.

    Args:
        results (list): List of tuples (filename, page_count)
        total_pages (int): Total number of pages

    Returns:
        str: Markdown formatted report
    """
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    markdown = f"""# PDF Page Count Report

**Generated on:** {timestamp}

## Summary

- **Total PDF files:** {len(results)}
- **Total pages:** {total_pages}

## Detailed Results

| File Name | Page Count |
|-----------|------------|
"""

    for filename, page_count in results:
        markdown += f"| `{filename}` | {page_count} |\n"

    # Calculate statistics
    valid_results = [r for r in results if isinstance(r[1], int) and r[1] > 0]

    if valid_results:
        avg_pages = total_pages / len(valid_results)
        largest_file = max(valid_results, key=lambda x: x[1])
        smallest_file = min(valid_results, key=lambda x: x[1])

        markdown += f"""
## Statistics

- **Average pages per file:** {avg_pages:.1f}
- **Largest file:** {largest_file[0]} ({largest_file[1]} pages)
- **Smallest file:** {smallest_file[0]} ({smallest_file[1]} pages)
"""
    else:
        markdown += """
## Statistics

- **Average pages per file:** N/A
- **Largest file:** N/A
- **Smallest file:** N/A
"""

    markdown += """
---
*Report generated by Count PDF Page*
"""

    return markdown


def process_directory(
    directory: Union[str, None] = None,
) -> Tuple[List[Tuple[str, Union[int, str]]], int]:
    """
    Process all PDF files in a directory and return results.

    Args:
        directory (str, optional): Directory to scan. Defaults to current directory.

    Returns:
        tuple: (results list, total pages count)
    """
    import glob

    if directory is None:
        directory = os.getcwd()

    # Change to target directory
    original_dir = os.getcwd()
    os.chdir(directory)

    try:
        # Find all PDF files
        pdf_files = glob.glob("*.pdf")

        if not pdf_files:
            return [], 0

        # Count pages for each PDF
        results: List[Tuple[str, Union[int, str]]] = []
        total_pages = 0

        for pdf_file in sorted(pdf_files):
            page_count = count_pdf_pages(pdf_file)

            if page_count > 0:
                results.append((pdf_file, page_count))
                total_pages += page_count
            else:
                results.append((pdf_file, "Error"))

        return results, total_pages

    finally:
        # Restore original directory
        os.chdir(original_dir)
