"""mldash CLI — command-line interface for ML-Dash SDK."""

import sys

try:
    import click
except ImportError:
    print("Error: click is required for the CLI. Install: pip install click")
    sys.exit(1)


@click.group()
@click.version_option(package_name="mldash-sdk")
def main():
    """ML-Dash SDK command-line interface."""
    pass


@main.command()
@click.option("--port", default=0, help="WebSocket port (0 = auto-select)")
@click.option("--url", default=None, help="ML-Dash server URL")
@click.option("--api-key", default=None, help="API key")
def connect(port, url, api_key):
    """Start the local compute bridge for ML-Dash Studio.

    Code written in ML-Dash Studio will execute on this machine.
    """
    from ._connect import start_bridge
    start_bridge(port=port, url=url, api_key=api_key)


@main.command()
@click.option("--url", default=None, help="ML-Dash server URL")
@click.option("--api-key", default=None, help="API key")
def login(url, api_key):
    """Authenticate with ML-Dash and store credentials."""
    import mldash
    mldash.login(url=url, api_key=api_key)


@main.command()
def logout():
    """Remove stored credentials."""
    import mldash
    mldash.logout()


@main.command()
def whoami():
    """Show current authentication status."""
    import mldash
    mldash.whoami()


@main.command()
@click.option("--force", is_flag=True, help="Recreate the environment from scratch")
@click.option("--no-autocomplete", is_flag=True, help="Skip autocomplete model download")
def setup(force, no_autocomplete):
    """Create a managed Python environment with common ML packages.

    Installs pandas, numpy, scikit-learn, matplotlib, seaborn, and mldash-sdk
    into ~/.mldash/venv/. The bridge (mldash connect) auto-uses this environment.

    Also installs llama-cpp-python and downloads the Qwen2.5-Coder-1.5B model
    for local AI autocomplete (use --no-autocomplete to skip).
    """
    from ._setup import run_setup
    run_setup(force=force, no_autocomplete=no_autocomplete)


@main.command()
@click.argument("packages", nargs=-1, required=True)
def install(packages):
    """Install additional packages into the managed environment.

    Example: mldash install xgboost tensorflow
    """
    from ._setup import run_install
    run_install(list(packages))


if __name__ == "__main__":
    main()
