"""CLI entry point for anki-yaml-sync."""

import logging
import sys

import click
from click_aliases import ClickAliasedGroup

from . import __version__
from .commands.export_cmd import export_notes
from .commands.import_cmd import import_notes


# Setup logging
def setup_logging(verbose: bool = False):
    """Configure logging."""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(level=level, format="%(levelname)s: %(message)s")


@click.group(cls=ClickAliasedGroup, invoke_without_command=True)
@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output")
@click.option("--version", is_flag=True, help="Show version")
@click.pass_context
def main(ctx, verbose, version):
    """Anki YAML Sync - Import/export Anki notes as YAML files."""

    if version:
        print(f"anki-yaml-sync version {__version__}")
        sys.exit(0)

    setup_logging(verbose)

    if ctx.invoked_subcommand is None:
        print(ctx.get_help())


@main.command(name="import", aliases=["get-from-anki", "fetch", "gfa", "f"])
@click.option(
    "--output-dir",
    "-o",
    default="notes",
    help="Directory to save YAML files (default: notes)",
)
def import_cmd(output_dir):
    """Import notes from Anki and save as YAML files."""
    try:
        import_notes(output_dir)
    except Exception:  # pylint: disable=broad-exception-caught
        sys.exit(1)


@main.command(name="export", aliases=["send-to-anki", "push", "sta", "p"])
@click.option(
    "--input-dir",
    "-i",
    default="notes",
    help="Directory containing YAML files (default: notes)",
)
@click.option(
    "--deck", default="Default", help="Deck to add new notes to (default: Default)"
)
def export_cmd(input_dir, deck):
    """Sync YAML files back to Anki."""
    try:
        export_notes(input_dir, deck)
    except Exception:  # pylint: disable=broad-exception-caught
        sys.exit(1)


if __name__ == "__main__":
    main()  # pylint: disable=no-value-for-parameter
