"""CLI entry point for Condensr."""

from pathlib import Path

import click

from condensr import get_chapters, summarize
from condensr.parser import get_book_title


@click.command()
@click.argument("pdf_path", type=click.Path(exists=True))
@click.option(
    "--output", "-o",
    type=click.Path(writable=True),
    default=None,
    help="Output file path. Default: <book>-summary.md in current directory.",
)
@click.option(
    "--model", "-m",
    default="mistral-small-latest",
    help="Mistral model name.",
)
def main(pdf_path, output, model):
    """Summarize a PDF book chapter by chapter."""
    if output is None:
        output = str(Path.cwd() / f"{Path(pdf_path).stem}-summary.md")

    title = get_book_title(pdf_path)
    chapter_titles = get_chapters(pdf_path)
    total = len(chapter_titles) if chapter_titles else 1

    click.echo(f"Writing summary to {output}", err=True)

    with open(output, "w", encoding="utf-8") as f:
        f.write(f"# {title}\n\n")
        for i, (chapter_title, summary) in enumerate(summarize(pdf_path, model=model), 1):
            click.echo(
                f"Summarizing chapter {i}/{total}: {chapter_title}...", err=True
            )
            f.write(f"## {chapter_title}\n\n{summary}\n\n")

    click.echo("Done.", err=True)
