import click

from gsearch_mcp_cli import __version__
from gsearch_mcp_cli.cli.ai_cmd import ai_cmd
from gsearch_mcp_cli.cli.ai_doc import get_ai_doc
from gsearch_mcp_cli.cli.config_cmd import config_cmd
from gsearch_mcp_cli.cli.doctor_cmd import doctor_cmd
from gsearch_mcp_cli.cli.fetch_cmd import fetch_cmd
from gsearch_mcp_cli.cli.search_cmd import search_cmd
from gsearch_mcp_cli.cli.setup_cmd import setup_cmd
from gsearch_mcp_cli.cli.skill_cmd import skill_cmd


def _print_docs(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    click.echo(get_ai_doc(__version__))
    ctx.exit()


class DefaultSearchGroup(click.Group):
    """Click group that falls back to 'search' for unknown commands."""

    def parse_args(self, ctx, args):
        if args and not args[0].startswith("-"):
            if args[0] not in self.commands:
                args = ["search"] + args
        return super().parse_args(ctx, args)


@click.group(cls=DefaultSearchGroup, invoke_without_command=True)
@click.version_option(__version__, prog_name="gsearch")
@click.option("--ai", is_flag=True, callback=_print_docs, expose_value=False,
              is_eager=True, help="Print AI-optimized documentation")
@click.option("--verbose", is_flag=True, default=False, help="Enable debug logging")
@click.pass_context
def cli(ctx, verbose):
    """gsearch — Google Search CLI for AI agents."""
    ctx.ensure_object(dict)
    ctx.obj["verbose"] = verbose

    if verbose:
        import logging
        logging.basicConfig(level=logging.DEBUG)

    if ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())


cli.add_command(search_cmd, "search")
cli.add_command(ai_cmd, "ai")
cli.add_command(fetch_cmd, "fetch")
cli.add_command(skill_cmd, "skill")
cli.add_command(setup_cmd, "setup")
cli.add_command(config_cmd, "config")
cli.add_command(doctor_cmd, "doctor")


def main():
    cli()


if __name__ == "__main__":
    main()
