"""Extract text from EPUB files using ebooklib and BeautifulSoup."""

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import ebooklib
from bs4 import BeautifulSoup
from ebooklib import epub

from output_utils import output_to_file_or_stdout


def extract(epub_path: str) -> list[dict]:
    """Return list of {"chapter": int, "title": str, "text": str} for each document item."""
    book = epub.read_epub(epub_path)
    results = []
    chapter_num = 0

    for item in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):
        soup = BeautifulSoup(item.get_content(), "html.parser")
        text = soup.get_text(separator="\n", strip=True)

        if not text:
            continue

        chapter_num += 1
        title = ""
        heading = soup.find(["h1", "h2", "h3"])
        if heading:
            title = heading.get_text(strip=True)

        results.append({
            "chapter": chapter_num,
            "title": title,
            "text": text,
        })

    return results


def _chapters_to_pages(chapters: list[dict]) -> list[dict]:
    """Adapt chapter output to page-based format for txt/md writers."""
    return [{"page": c["chapter"], "text": c["text"]} for c in chapters]


def main():
    parser = argparse.ArgumentParser(description="Extract text from EPUB files")
    parser.add_argument("epub", help="Path to input EPUB")
    parser.add_argument("output", nargs="?", default=None, help="Output file path")
    parser.add_argument("--format", choices=["txt", "json", "md"], default="txt",
                        dest="fmt", help="Output format (default: txt)")
    args = parser.parse_args()

    chapters = extract(args.epub)

    if args.fmt == "json":
        data = {"extractor": "epub", "chapters": chapters}
    else:
        data = _chapters_to_pages(chapters)

    output_to_file_or_stdout(data, args.fmt, args.output)


if __name__ == "__main__":
    main()
