"""Condensr — Summarize books chapter by chapter using AI."""

import time
from importlib.metadata import PackageNotFoundError, version

from condensr.parser import detect_chapters, extract_chapter_text, extract_full_text, get_book_title
from condensr.summarizer import summarize_text

try:
    __version__ = version("condensr")
except PackageNotFoundError:
    __version__ = "unknown"

_REQUEST_INTERVAL = 1.0  # seconds between API calls (Mistral free tier: ~1 req/s)


def get_chapters(pdf_path: str) -> list[str]:
    """Detect and return chapter titles from a PDF.

    Uses heuristic detection only (no API calls).
    Returns an empty list if no chapters are found.

    Args:
        pdf_path: Path to the PDF file.

    Returns:
        List of chapter title strings.

    Example::

        >>> import condensr
        >>> condensr.get_chapters("book.pdf")
        ["Introduction", "Chapter 1: Origins", "Chapter 2: Growth"]
    """
    chapters = detect_chapters(pdf_path)
    return [c.title for c in chapters]


def summarize(
    pdf_path: str,
    *,
    model: str = "mistral-small-latest",
    api_key: str | None = None,
    on_chapter=None,
):
    """Summarize a PDF book chapter by chapter.

    Yields (chapter_title, summary_markdown) tuples as each chapter completes.
    If no chapters are detected, summarizes the entire book as one unit.

    Always returns a generator. If ``on_chapter`` is provided, the callback
    fires before each yield.

    Args:
        pdf_path: Path to the PDF file.
        model: Mistral model name (default: "mistral-small-latest").
        api_key: Mistral API key. Falls back to MISTRAL_API_KEY env var.
        on_chapter: Optional callback(title, summary) fired before each yield.

    Yields:
        Tuples of (chapter_title, summary_markdown).

    Example::

        >>> import condensr
        >>> for title, summary in condensr.summarize("book.pdf"):
        ...     print(f"## {title}\\n{summary}")
    """
    chapters = detect_chapters(pdf_path)

    if not chapters:
        # No chapters detected — summarize entire book as one unit
        text = extract_full_text(pdf_path)
        title = get_book_title(pdf_path)
        summary = summarize_text(text, title, model=model, api_key=api_key)
        if on_chapter:
            on_chapter(title, summary)
        yield (title, summary)
        return

    for i, chapter in enumerate(chapters):
        if i > 0:
            time.sleep(_REQUEST_INTERVAL)
        text = extract_chapter_text(pdf_path, chapter)
        summary = summarize_text(text, chapter.title, model=model, api_key=api_key)
        if on_chapter:
            on_chapter(chapter.title, summary)
        yield (chapter.title, summary)
