"""
pptx_export.py

tkpptx の共通コマンドラインインターフェース。

officecli
PowerShell> irm https://raw.githubusercontent.com/iOfficeAI/OfficeCLI/main/install.ps1 | iex
> npm install -g @officecli/officecli



python pptx_export.py --list-backends
python pptx_export.py input.pptx output.pdf --backend com
python pptx_export.py input.pptx output.pdf --backend libreoffice
python pptx_export.py input.pptx slides --format images --backend officecli --render native --width 1920
python pptx_export.py input.pptx input.html --backend officecli


PDF 変換
--------
python pptx_export.py pdf input.pptx
python pptx_export.py pdf input.pptx output.pdf --backend com
python pptx_export.py pdf input.pptx output.pdf --backend officecli

画像変換
--------
python pptx_export.py images input.pptx
python pptx_export.py images input.pptx slides --backend com --format png
python pptx_export.py images input.pptx slides \
    --backend officecli --render html --width 1920

バックエンド
------------
com:
    Windows + Microsoft PowerPoint + comtypes
officecli:
    OfficeCLI。PPTX のみ
auto:
    OfficeCLI を試し、失敗時に COM へフォールバック
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from tkpptx import (
    ExportOptions,
    TkPptxError,
    available_backends,
    export_html,
    export_images,
    export_pdf,
)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description=(
            "Export PowerPoint files through PowerPoint COM, OfficeCLI, "
            "or LibreOffice."
        )
    )
    parser.add_argument("input", nargs="?", help="Input .ppt/.pptx file")
    parser.add_argument("output", nargs="?", help="Output file or directory")
    parser.add_argument(
        "--backend",
        choices=["auto", "com", "officecli", "libreoffice"],
        default="auto",
        help="Export backend (default: auto)",
    )
    parser.add_argument(
        "--format",
        choices=["pdf", "images", "html"],
        help="Output format. Inferred from output extension when omitted.",
    )
    parser.add_argument("--start", type=int, default=1)
    parser.add_argument("--end", type=int)
    parser.add_argument("--width", type=int, default=1920)
    parser.add_argument("--height", type=int)
    parser.add_argument("--dpi", type=int, default=150)
    parser.add_argument(
        "--render",
        default="native",
        help="OfficeCLI screenshot renderer (default: native)",
    )
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Replace existing output files.",
    )
    parser.add_argument(
        "--list-backends",
        action="store_true",
        help="Show detected backends and exit.",
    )
    return parser


def infer_format(output: str) -> str:
    suffix = Path(output).suffix.lower()
    if suffix == ".pdf":
        return "pdf"
    if suffix in {".html", ".htm"}:
        return "html"
    if suffix == "":
        return "images"
    raise ValueError(
        "Could not infer output format. Use --format pdf|images|html."
    )


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    if args.list_backends:
        states = available_backends()
        for name, enabled in states.items():
            print(f"{name:12s}: {'available' if enabled else 'not available'}")
        return 0

    if not args.input or not args.output:
        parser.error("input and output are required unless --list-backends is used.")

    operation = args.format or infer_format(args.output)
    options = ExportOptions(
        start=args.start,
        end=args.end,
        width=args.width,
        height=args.height,
        dpi=args.dpi,
        overwrite=args.overwrite,
        render=args.render,
    )

    try:
        if operation == "pdf":
            result = export_pdf(
                args.input,
                args.output,
                backend=args.backend,
                options=options,
            )
            print(f"Created PDF: {result}")

        elif operation == "html":
            result = export_html(
                args.input,
                args.output,
                backend=args.backend,
                options=options,
            )
            print(f"Created HTML: {result}")

        else:
            results = export_images(
                args.input,
                args.output,
                backend=args.backend,
                options=options,
            )
            print(f"Created {len(results)} image(s) in: {Path(args.output).resolve()}")
            for item in results:
                print(f"  {item}")

    except (TkPptxError, OSError, ValueError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
