"""Extract text from legacy ebook formats (.lit, .prc, .mobi) via Calibre conversion.

Requires `ebook-convert` from Calibre to be installed and on PATH.
Converts the input file to EPUB in a temp directory, then delegates to the epub extractor.
"""

import argparse
import os
import shutil
import subprocess
import sys
import tempfile

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

from extractors.epub import extract as epub_extract
from output_utils import output_to_file_or_stdout

SUPPORTED_EXTENSIONS = {".lit", ".prc", ".mobi"}


def _require_calibre():
    """Verify ebook-convert is available."""
    if not shutil.which("ebook-convert"):
        print(
            "error: 'ebook-convert' not found on PATH.\n"
            "Install Calibre: https://calibre-ebook.com/download",
            file=sys.stderr,
        )
        sys.exit(1)


def extract(ebook_path: str) -> list[dict]:
    """Convert to EPUB via Calibre, then extract chapters.

    Returns list of {"chapter": int, "title": str, "text": str}.
    """
    _require_calibre()

    with tempfile.TemporaryDirectory() as tmpdir:
        epub_path = os.path.join(tmpdir, "converted.epub")
        result = subprocess.run(
            ["ebook-convert", ebook_path, epub_path],
            capture_output=True,
            text=True,
        )
        if result.returncode != 0:
            raise RuntimeError(
                f"ebook-convert failed (exit {result.returncode}):\n{result.stderr}"
            )

        return epub_extract(epub_path)


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 legacy ebook formats (.lit, .prc, .mobi)"
    )
    parser.add_argument("ebook", help="Path to input ebook file")
    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.ebook)

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

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


if __name__ == "__main__":
    main()
