import argparse
import subprocess
import logging
import time
import os


# Set up logging
logger = logging.getLogger(__name__)


def set_logger(external_logger):
    global logger
    logger = external_logger


def cleanup_logs():
    try:
        for handler in logger.handlers:
            if hasattr(handler, "flush"):
                handler.flush()

        time.sleep(1.5)

        logging.shutdown()
    except Exception as e:
        logger.error(f"Error during log cleanup: {e}")


def create_parser() -> argparse.ArgumentParser:
    """Creates a parser for the command line arguments.

    Returns:
        argparse.ArgumentParser: The parser for the command line arguments.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--code",
        help="Unique code to allow connection via CRD with specific Google login.",
        type=str,
        default=None,
    )

    return parser


def construct_command(args) -> str:
    """Constructs the Linux CRD command to connect to a remote machine.

    Args:
        args (argparse.Namespace): The command line arguments.

    Returns:
        str: The Linux CRD command to connect to a remote machine.
    """

    redirect_url = "'https://remotedesktop.google.com/_/oauthredirect'"
    name = os.getenv("VM_NAME", "$(hostname)")

    if args.code is None:
        raise ValueError("Code must be provided to construct the command.")

    command = "DISPLAY= /opt/google/chrome-remote-desktop/start-host"
    command += f" --code={args.code}"
    command += f" --redirect-url={redirect_url}"
    command += f" --name={name}"

    return command


def reconstruct_command(command: str) -> str:
    """Reconstructs the Chrome Remote Desktop command.

    Args:
        command (str): CRD command to connect to the machine.

    Returns:
        str: Reconstructed command to connect to the machine.
    """
    arg_to_parse = command.split()

    # Parse the command line arguments
    parser = create_parser()
    args, _ = parser.parse_known_args(args=arg_to_parse)

    logger.debug(vars(args))

    # Construct the command to be executed
    command = construct_command(args)
    logger.debug(f"Command to be executed: {command}")

    return command


def connect_to_crd(command, pin):
    # Parse the command line arguments
    command = reconstruct_command(command)

    # input the pin code with verification
    input_pin = pin + "\n"
    input_pin_verification = input_pin + input_pin

    # Execute the command
    result = subprocess.run(
        command,
        input=input_pin_verification,
        shell=True,
        capture_output=True,
        text=True,
    )

    # Check the result
    logger.debug(f"Output:\n {result.stdout}")

    if result.stderr:
        logger.error(f"Error: {result.stderr}")
