#!/usr/bin/env python
# (c) 2015-2023 Acellera Ltd http://www.acellera.com
# All Rights Reserved
# Distributed under HTMD Software License Agreement
# No redistribution in whole or part
#
"""Command line interface for PlayMolecule."""

import argparse
import os
import sys
import getpass
import logging

logger = logging.getLogger(__name__)


def _login_command(args):
    """Handle the login command."""
    from playmolecule._backends._http import login

    # Get email from args or environment
    email = args.email
    if not email:
        email = os.environ.get("PLAYMOLECULE_EMAIL", os.environ.get("PM_EMAIL"))

    if not email:
        print(
            "Error: Email is required. Provide it via --email or PLAYMOLECULE_EMAIL/PM_EMAIL environment variable."
        )
        sys.exit(1)

    # Get password from args or environment
    password = args.password
    if not password:
        password = os.environ.get(
            "PLAYMOLECULE_PASSWORD", os.environ.get("PM_PASSWORD")
        )

    if not password:
        # If no password provided, prompt for it
        password = getpass.getpass("Password: ")

    try:
        login(email, password)
        print(f"Successfully logged in as {email}")
    except Exception as e:
        print(f"Login failed: {e}")
        sys.exit(1)


def _logout_command(args):
    """Handle the logout command."""
    from playmolecule._backends._http import logout

    try:
        logout()
        print("Successfully logged out")
    except Exception as e:
        print(f"Logout failed: {e}")
        sys.exit(1)


def _cli_main():
    """Main entry point for the CLI."""
    parser = argparse.ArgumentParser(
        description="PlayMolecule command line interface",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # Login command
    login_parser = subparsers.add_parser(
        "login",
        help="Login to PlayMolecule backend",
        description="Login to PlayMolecule backend using email and password. "
        "Credentials can be provided via command line arguments or environment variables "
        "(PLAYMOLECULE_EMAIL/PM_EMAIL and PLAYMOLECULE_PASSWORD/PM_PASSWORD).",
    )
    login_parser.add_argument(
        "--email",
        help="Email address for login. Can also be set via PLAYMOLECULE_EMAIL or PM_EMAIL environment variable.",
    )
    login_parser.add_argument(
        "--password",
        help="Password for login. Can also be set via PLAYMOLECULE_PASSWORD or PM_PASSWORD environment variable. "
        "If not provided, you will be prompted.",
    )
    login_parser.set_defaults(func=_login_command)

    # Logout command
    logout_parser = subparsers.add_parser(
        "logout", help="Logout from PlayMolecule backend"
    )
    logout_parser.set_defaults(func=_logout_command)

    # Parse arguments
    args = parser.parse_args()

    # If no command specified, show help
    if not hasattr(args, "func"):
        parser.print_help()
        sys.exit(0)

    # Execute the command
    args.func(args)


if __name__ == "__main__":
    _cli_main()
