"""peasy-convert CLI — Unified entry point for all Peasy tools.

Usage::

    peasy pdf merge file1.pdf file2.pdf -o merged.pdf
    peasy image resize input.png --width 800 -o output.png
    peasy text reverse "Hello World"
    peasy css gradient --colors "#ff6b35" "#2ec4b6"
    peasy --version
"""

from __future__ import annotations

import typer

app = typer.Typer(
    name="peasy",
    help="Unified CLI for Peasy tools — PDF, image, text, and CSS utilities.",
    no_args_is_help=True,
    pretty_exceptions_enable=False,
)


def _version_callback(value: bool) -> None:
    if value:
        from peasy_convert import __version__

        typer.echo(f"peasy-convert {__version__}")
        raise typer.Exit


@app.callback()
def main(
    version: bool = typer.Option(
        False,
        "--version",
        "-V",
        help="Show version and exit.",
        callback=_version_callback,
        is_eager=True,
    ),
) -> None:
    """Peasy — All your file & text tools in one CLI."""


# ── Mount sub-commands from installed packages ──────────────────


def _register_pdf() -> None:
    try:
        from peasy_pdf.cli import app as pdf_app

        app.add_typer(pdf_app, name="pdf", help="PDF tools — merge, split, compress, rotate.")
    except ImportError:
        pass


def _register_image() -> None:
    try:
        from peasy_image.cli import app as image_app

        app.add_typer(image_app, name="image", help="Image tools — resize, crop, convert, filter.")
    except ImportError:
        pass


def _register_text() -> None:
    try:
        from peasytext.cli import app as text_app

        app.add_typer(text_app, name="text", help="Text tools — case, encode, hash, diff.")
    except ImportError:
        pass


def _register_css() -> None:
    try:
        from peasy_css.cli import app as css_app

        app.add_typer(css_app, name="css", help="CSS tools — gradient, shadow, flexbox, grid.")
    except ImportError:
        pass


_register_pdf()
_register_image()
_register_text()
_register_css()


@app.command()
def info() -> None:
    """Show installed Peasy packages and versions."""
    packages = [
        ("peasy-pdf", "peasy_pdf"),
        ("peasy-image", "peasy_image"),
        ("peasytext", "peasytext"),
        ("peasy-css", "peasy_css"),
    ]

    typer.echo("Peasy Convert — Installed packages:\n")

    from peasy_convert import __version__

    typer.echo(f"  peasy-convert  {__version__}")

    for display_name, module_name in packages:
        try:
            mod = __import__(module_name)
            version = getattr(mod, "__version__", "?")
            typer.echo(f"  {display_name:<14}  {version}")
        except ImportError:
            typer.echo(f"  {display_name:<14}  (not installed)")

    typer.echo("\nInstall extras: pip install 'peasy-convert[all]'")
