import logging
from importlib.metadata import entry_points, version

import typer

from .login import login, jwt
from .account import account_app
from .auxiliary import marmot, docs
from .service_principal import service_principal_app
from .feedback import feedback
from .kom_mcp import mcp_app
from .plugin import plugin_app
from .sql import sql_execute, sql_shell
from .cohort_exploration import cohort_exploration

logger = logging.getLogger(__name__)

__version__ = version("komodo")

app = typer.Typer(
    name="komodo",
    help="Komodo CLI - Build the evidentiary standard",
    add_completion=False,
    invoke_without_command=True,
)


@app.callback()
def callback(ctx: typer.Context, version: bool = typer.Option(False, "--version", "-v", help="Show the version and exit.")):
    """
    Komodo CLI - A command-line interface for managing Komodo workspaces.

    Use this CLI to:
    • Login and manage authentication
    • Set and get account information
    • Explore Snowflake data via MCP
    • Run SQL queries against Snowflake
    """
    if version:
        typer.echo(f"Komodo CLI Version: {__version__}")
        raise typer.Exit()
    if ctx.invoked_subcommand is None:
        typer.echo(ctx.get_help())
        raise typer.Exit()


app.command()(login)
app.command()(jwt)
app.command()(marmot)
app.command()(docs)
app.command()(feedback)
app.add_typer(account_app, name="account")
app.add_typer(service_principal_app, name="service-principal")
app.add_typer(mcp_app, name="mcp")
app.add_typer(plugin_app, name="plugin")
app.command()(sql_execute)
app.command()(sql_shell)

beta_app = typer.Typer(
    name="beta",
    help="[yellow]\u26a0\ufe0f  Beta commands[/yellow] - Preview features that are more stable than alpha but still subject to change.",
    rich_markup_mode="rich",
    no_args_is_help=True,
)


@beta_app.callback()
def beta_callback(ctx: typer.Context):
    """
    BETA COMMANDS

    These commands are beta preview features:
    \u2022 They are more stable than alpha but may still change in breaking ways
    \u2022 They could be removed or modified without notice
    \u2022 Access is limited to select users during the beta period

    For production use cases, please contact the Komodo team.
    """
    if ctx.invoked_subcommand:
        from komodo.preview.utils import show_preview_warning
        from rich.console import Console

        console = Console()
        show_preview_warning(console, "beta", feature_name=f"komodo beta {ctx.invoked_subcommand}")


beta_app.command(name="cohort-exploration")(cohort_exploration)
app.add_typer(beta_app, name="beta")

for ep in entry_points(group="komodo.cli_plugins"):
    try:
        register_fn = ep.load()
        register_fn(app)
        logger.debug(f"Loaded CLI plugin: {ep.name}")
    except Exception as e:
        logger.debug(f"Failed to load CLI plugin '{ep.name}': {e}")

if __name__ == "__main__":
    app()
