#!python

# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
# SPDX-License-Identifier: MIT

import argparse
import numpy as np
import os
import sys
import time
import warnings

from glob import glob

from emle import _supported_backends
from emle._socket import Socket

# Deprecated options previously accepted by EMLECalculator / emle-server.
DEPRECATED_OPTIONS = {
    "rascal_model": "the Rascal backend has been removed",
    "atomic_numbers": "it is no longer used",
}


# Copied from distutils.util.strtobool, which is deprecated.
def strtobool(val):
    """Convert a string representation of truth to true (1) or false (0).

    True values are case insensitive 'y', 'yes', 't', 'true', 'on', and '1'.
    false values are case insensitive 'n', 'no', 'f', 'false', 'off', and '0'.
    Raises ValueError if 'val' is anything else.
    """
    val = val.replace(" ", "").lower()
    if val in ("y", "yes", "t", "true", "on", "1"):
        return True
    elif val in ("n", "no", "f", "false", "off", "0"):
        return False
    else:
        raise ValueError("invalid truth value %r" % (val,))


# Check whether any EMLE environment variables are set.
config = os.getenv("EMLE_CONFIG")
host = os.getenv("EMLE_HOST")
try:
    port = int(os.getenv("EMLE_PORT"))
except:
    port = None
model = os.getenv("EMLE_MODEL")
method = os.getenv("EMLE_METHOD")
alpha_mode = os.getenv("EMLE_ALPHA_MODE")
try:
    use_dipoles = strtobool(os.getenv("EMLE_USE_DIPOLES"))
except:
    use_dipoles = False
mm_charges = os.getenv("EMLE_MM_CHARGES")
try:
    num_clients = int(os.getenv("EMLE_NUM_CLIENTS"))
except:
    num_clients = None
backend = os.getenv("EMLE_BACKEND")
external_backend = os.getenv("EMLE_EXTERNAL_BACKEND")
plugin_path = os.getenv("EMLE_PLUGIN_PATH")
device = os.getenv("EMLE_DEVICE")
try:
    energy_frequency = int(os.getenv("EMLE_ENERGY_FREQUENCY"))
except:
    energy_frequency = 0
energy_file = os.getenv("EMLE_ENERGY_FILE")
log_level = os.getenv("EMLE_LOG_LEVEL")
log_file = os.getenv("EMLE_LOG_FILE")
save_settings = os.getenv("EMLE_SAVE_SETTINGS")
orca_template = os.getenv("EMLE_ORCA_TEMPLATE")
deepmd_model = os.getenv("EMLE_DEEPMD_MODEL")
deepmd_deviation = os.getenv("EMLE_DEEPMD_DEVIATION")
deepmd_deviation_threshold = os.getenv("EMLE_DEEPMD_DEVIATION_THRESHOLD")
qbc_deviation = os.getenv("EMLE_QBC_DEVIATION")
qbc_deviation_threshold = os.getenv("EMLE_QBC_DEVIATION_THRESHOLD")
qm_xyz_file = os.getenv("EMLE_QM_XYZ_FILE")
pc_xyz_file = os.getenv("EMLE_PC_XYZ_FILE")
try:
    qm_xyz_frequency = int(os.getenv("EMLE_QM_XYZ_FREQUENCY"))
except:
    qm_xyz_frequency = 0
try:
    ani2x_model_index = int(os.getenv("EMLE_ANI2X_MODEL_INDEX"))
except:
    ani2x_model_index = None
try:
    mace_model = os.getenv("EMLE_MACE_MODEL")
except:
    mace_model = None
try:
    ace_model = os.getenv("EMLE_ACE_MODEL")
except:
    ace_model = None
parm7 = os.getenv("EMLE_PARM7")
try:
    lambda_interpolate = [
        float(x) for x in os.getenv("EMLE_LAMBDA_INTERPOLATE").split(",")
    ]
except:
    lambda_interpolate = None
try:
    interpolate_steps = int(os.getenv("EMLE_INTERPOLATE_STEPS"))
except:
    interpolate_steps = None
qm_indices = os.getenv("EMLE_QM_INDICES")
sqm_theory = os.getenv("EMLE_SQM_THEORY")
aimnet2_model = os.getenv("EMLE_AIMNET2_MODEL")
omnip2x_model = os.getenv("EMLE_OMNIP2X_MODEL")
try:
    electronic_state = int(os.getenv("EMLE_ELECTRONIC_STATE"))
except:
    electronic_state = None
try:
    model_charges = [int(x) for x in os.getenv("EMLE_MODEL_CHARGES").split(",")]
except:
    model_charges = None
try:
    model_mults = [int(x) for x in os.getenv("EMLE_MODEL_MULTS").split(",")]
except:
    model_mults = None
try:
    model_states = [int(x) for x in os.getenv("EMLE_MODEL_STATES").split(",")]
except:
    model_states = None
orca_path = os.getenv("EMLE_ORCA_PATH")
try:
    restart = strtobool(os.getenv("EMLE_RESTART"))
except:
    restart = False
try:
    retries = int(os.getenv("EMLE_RETRIES"))
except:
    retries = None

# Fallback to default values.
if not host:
    host = "localhost"
if not port:
    port = 10000
if not num_clients:
    num_clients = 1
if not retries:
    retries = 100

# Assemble the environment variables into a dictionary.
env = {
    "host": host,
    "port": port,
    "model": model,
    "method": method,
    "alpha_mode": alpha_mode,
    "use_dipoles": use_dipoles,
    "mm_charges": mm_charges,
    "num_clients": num_clients,
    "backend": backend,
    "external_backend": external_backend,
    "plugin_path": plugin_path,
    "device": device,
    "deepmd_model": deepmd_model,
    "deepmd_deviation": deepmd_deviation,
    "deepmd_deviation_threshold": deepmd_deviation_threshold,
    "qbc_deviation": qbc_deviation,
    "qbc_deviation_threshold": qbc_deviation_threshold,
    "qm_xyz_file": qm_xyz_file,
    "pc_xyz_file": pc_xyz_file,
    "qm_xyz_frequency": qm_xyz_frequency,
    "ani2x_model_index": ani2x_model_index,
    "mace_model": mace_model,
    "ace_model": ace_model,
    "lambda_interpolate": lambda_interpolate,
    "interpolate_steps": interpolate_steps,
    "parm7": parm7,
    "qm_indices": qm_indices,
    "sqm_theory": sqm_theory,
    "aimnet2_model": aimnet2_model,
    "omnip2x_model": omnip2x_model,
    "electronic_state": electronic_state,
    "model_charges": model_charges,
    "model_mults": model_mults,
    "model_states": model_states,
    "orca_path": orca_path,
    "restart": restart,
    "orca_template": orca_template,
    "energy_frequency": energy_frequency,
    "energy_file": energy_file,
    "log_level": log_level,
    "log_file": log_file,
    "save_settings": save_settings,
}


def validate_clients(num_clients):
    try:
        num_clients = int(num_clients)
    except:
        raise argparse.ArgumentTypeError(
            f"--num-clients: invalid int value: '{num_clients}'"
        )

    if num_clients < 0:
        raise argparse.ArgumentTypeError("--num-clients: Value must be >= 0")


# create argument parser.
parser = argparse.ArgumentParser(description="EMLE server")

# parse command-line options
parser.add_argument(
    "--config", type=str, help="path to a YAML configuration file", required=False
)
parser.add_argument("--host", type=str, help="the hostname", required=False)
parser.add_argument("--port", type=str, help="the port number", required=False)
parser.add_argument(
    "--model", type=str, help="path to an EMLE model file", required=False
)
parser.add_argument(
    "--method",
    type=str,
    help="the embedding method to use",
    choices=["electrostatic", "mechanical", "nonpol", "mm"],
    required=False,
)
parser.add_argument(
    "--alpha-mode",
    type=str,
    help=(
        "the alpha mode to use for the embedding method "
        "('species'/'reference' are deprecated aliases for 'fixed'/'flexible')"
    ),
    choices=["fixed", "flexible", "species", "reference"],
    required=False,
)
parser.add_argument(
    "--mm-charges",
    type=str,
    nargs="*",
    help="mm charges for atoms in the qm region in units of electron volt",
    required=False,
)
parser.add_argument(
    "--box",
    type=float,
    nargs="*",
    help="Box size in A (full ML DeepMD only)",
    required=False,
)
parser.add_argument(
    "--num-clients",
    type=validate_clients,
    help="the maximum number of client connections to allow",
    required=False,
)
parser.add_argument(
    "--backend",
    type=str,
    nargs="*",
    help="the in vacuo backend",
    choices=_supported_backends,
    required=False,
)
parser.add_argument(
    "--external-backend",
    type=str,
    help="the external backend as a Python callback function, e.g. 'module.function'",
    required=False,
)
parser.add_argument(
    "--plugin-path",
    type=str,
    help="a path containing any modules/scripts for external backends",
    required=False,
)
parser.add_argument(
    "--device",
    type=str,
    help="the device to be used by PyTorch",
    choices=["cpu", "cuda"],
    required=False,
)
parser.add_argument(
    "--ani2x-model-index",
    type=int,
    help="the index of the ANI2x model to use",
    required=False,
)
parser.add_argument(
    "--mace-model",
    type=str,
    help="name of the MACE-OFF23 model, or path to the MACE model file",
    required=False,
)
parser.add_argument(
    "--ace-model",
    type=str,
    help="path to the ACE model file",
    required=False,
)
parser.add_argument(
    "--deepmd-model",
    type=str,
    nargs="*",
    help="path to DeePMD model file(s) (first file is the reference model)",
    required=False,
)
parser.add_argument(
    "--deepmd-deviation",
    type=str,
    help="path to a file to write the max deviation between forces predicted with the DeePMD models",
    required=False,
)
parser.add_argument(
    "--deepmd-deviation-threshold",
    type=float,
    help="the threshold for the max deviation between forces predicted with the DeePMD models",
    required=False,
)
parser.add_argument(
    "--qm-xyz-file",
    type=str,
    help="path to a file to write the QM region coordinates",
    required=False,
)
parser.add_argument(
    "--pc-xyz-file",
    type=str,
    help="path to a file to write the MM region coordinates and charges",
    required=False,
)
parser.add_argument(
    "--qm-xyz-frequency",
    type=int,
    help="the frequency of writing the QM region coordinates to file (0 to disable)",
    required=False,
)
parser.add_argument(
    "--lambda-interpolate",
    type=float,
    nargs="*",
    help="the initial value of lambda for interpolating between MM and EMLE potentials, or the min and max values",
    required=False,
)
parser.add_argument(
    "--interpolate-steps",
    type=int,
    help="the number of steps over which to interpolate lambda between its min and max values",
    required=False,
)
parser.add_argument(
    "--set-lambda-interpolate",
    type=float,
    help="the value of lambda for interpolating between MM and EMLE potentials",
    required=False,
)
parser.add_argument(
    "--parm7",
    type=str,
    help="path to the parm7 topology file for the QM region",
    required=False,
)
parser.add_argument(
    "--qm-indices",
    type=str,
    nargs="*",
    help="the zero-based indices of the atoms within the QM region",
    required=False,
)
parser.add_argument(
    "--sqm-theory",
    type=str,
    help="the semi-empirical theory to use for the QM region when using the SQM backend",
    required=False,
)
parser.add_argument(
    "--aimnet2-model",
    type=str,
    help="the AIMNet2 model name or file to use when using the AIMNet2 backend",
    required=False,
)
parser.add_argument(
    "--omnip2x-model",
    type=str,
    nargs="*",
    help="path to OMNI-P2x model file(s) to use when using the OMNI-P2x backend",
    required=False,
)
parser.add_argument(
    "--electronic-state",
    type=int,
    help="the electronic state index (0 is the ground state)",
    required=False,
)
parser.add_argument(
    "--model-charges",
    type=int,
    nargs="+",
    help="the QM charges that the in vacuo model supports",
    required=False,
)
parser.add_argument(
    "--model-mults",
    type=int,
    nargs="+",
    help="the spin multiplicities that the in vacuo model supports",
    required=False,
)
parser.add_argument(
    "--model-states",
    type=int,
    nargs="+",
    help="the electronic states that the in vacuo model supports",
    required=False,
)
parser.add_argument(
    "--orca-path",
    type=str,
    help="the path to the ORCA executable (required when using the ORCA backend)",
    required=False,
)
parser.add_argument(
    "--restart",
    action=argparse.BooleanOptionalAction,
    required=False,
)
parser.add_argument(
    "--orca-template",
    type=str,
    help="the path to a template ORCA input file (only used when using the ORCA backend via Sire)",
    required=False,
)
parser.add_argument(
    "--energy-frequency",
    type=int,
    help="The frequency of logging energies to file",
    required=False,
)
parser.add_argument(
    "--energy-file",
    type=str,
    help="The file to log energies to",
    required=False,
)
parser.add_argument(
    "--log-level",
    type=str,
    help="The logging level",
    choices=["TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
    required=False,
)
parser.add_argument(
    "--log-file",
    type=str,
    help="The file to log to",
    required=False,
)
parser.add_argument(
    "--save-settings",
    action=argparse.BooleanOptionalAction,
    required=False,
)
args = vars(parser.parse_args())

# Pop the config.
if args["config"] is not None:
    config = args.pop("config")

# Load the YAML config file.
if config is not None:
    # Convert to an absolute path.
    config = os.path.abspath(config)

    if not os.path.isfile(config):
        raise FileNotFoundError(f"Config file not found: '{config}'")

    # Try to read the config into a dictionary.
    try:
        import yaml

        with open(config, "r") as f:
            config = yaml.safe_load(f)

    except Exception as e:
        raise ValueError(f"Could not load YAML config file: {e}")

    # Remove deprecated options that are no longer accepted by EMLECalculator,
    # warning the user that they are being ignored.
    for option, reason in DEPRECATED_OPTIONS.items():
        if option in config:
            warnings.warn(
                f"'{option}' is deprecated since {reason}. "
                "This setting will be ignored.",
                FutureWarning,
            )
            del config[option]

    # Reparse the command-line arguments using the existing config
    # as a Namespace. Any non-default arguments from the command line
    # will override those in the config.
    args = vars(parser.parse_args(namespace=argparse.Namespace(**config)))

# Overload environment variables using command-line arguments, popping options
# that are specific to the server, not the EMLECalculator.
if args["host"] is not None:
    host = args.pop("host")
else:
    args.pop("host")
if args["port"] is not None:
    port = args.pop("port")
else:
    args.pop("port")
if args["num_clients"] is not None:
    num_clients = args.pop("num_clients")
else:
    args.pop("num_clients")
set_lambda_interpolate = args.pop("set_lambda_interpolate")
args.pop("config")

# Update any None value args with values from the environment variables.
for key, value in args.items():
    if value is None:
        try:
            args[key] = env[key]
        except:
            pass

# If the user has requested to set the interpolation lambda for an existing server,
# then do this first.
if set_lambda_interpolate is not None:
    # Create a socket and connect.
    sock = Socket()

    # Try to connect to the server. We try 100 times, waiting for 2 seconds
    # following each failure. This should (hopefully) give the server enough
    # time to start.
    is_connected = False
    for x in range(0, retries):
        try:
            print("Trying to establish a connection with the EMLE server...")
            sock.connect(host, port)
        except:
            print("Failed. Retrying in 2 seconds...")
            time.sleep(2)
        else:
            print("Connection established!")
            is_connected = True
            break

    if not is_connected:
        raise ConnectionError(
            f"Unable to connect to EMLE server at {host}:{port} "
            "Please check that it is running."
        )

    # Prepend the lambda update message.
    msg = f"emlelambda:{args.set_lambda_interpolate:.5f}"

    # Prepend the message length.
    msg = f"{len(msg)}:{msg}"

    print(
        f"Requesting EMLE server updates interpolation lambda to {set_lambda_interpolate:.5f}"
    )
    sock.send(msg, len(msg))

    msg, err = sock.receive()

    if msg == "emlelambdaset":
        print("Received notice that the EMLE server has updated lambda")
    elif msg == "emlefail":
        print("Received notice that the request failed.")
        print(f"[ERROR] {err}")
    else:
        raise RuntimeError(f"Invalid message received from EMLE server: '{msg}'")

    # Exit the script.
    sys.exit()


# Handle special case formatting for environment variables.

# Validate the MM charges.
if args["mm_charges"] is None:
    if method == "mm":
        raise ValueError("'mm_charges' are required when using 'mm' embedding")
    elif args["lambda_interpolate"] is not None:
        raise ValueError("'mm_charges' are required when interpolating")

else:
    # Whether we are parsing a list of charges, rather than a file.
    is_list = False

    if isinstance(args["mm_charges"], str):
        # If this isn't a path to a file, try splitting on commas.
        if not os.path.isfile(args["mm_charges"]) or not os.path.isfile(
            os.path.abspath(args["mm_charges"])
        ):
            try:
                args["mm_charges"] = args["mm_charges"].split(",")
                is_list = True
            except:
                raise ValueError(
                    "Unable to parse EMLE_MM_CHARGES environment variable as a comma-separated list of floats"
                )

    # A single entry list is assumed to be the path to a file.
    elif isinstance(args["mm_charges"], list):
        if len(args["mm_charges"]) == 1:
            args["mm_charges"] = args["mm_charges"][0]
        else:
            is_list = True

    # Try to parse lists of MM charges as a NumPy array of floats.
    if is_list:
        try:
            args["mm_charges"] = np.array([float(x) for x in args["mm_charges"]])
        except:
            raise TypeError("Unable to parse MM charges as an array of floats")

# Validate the QM indices.
if args["qm_indices"] is None:
    if args["lambda_interpolate"] is not None:
        raise ValueError("'qm_indices' are required when interpolating")

else:
    # Whether we are parsing a list of indices, rather than a file.
    is_list = False

    if isinstance(args["qm_indices"], str):
        # If this isn't a path to a file, try splitting on commas.
        if not os.path.isfile(args["qm_indices"]) or not os.path.isfile(
            os.path.abspath(args["qm_indices"])
        ):
            try:
                args["qm_indices"] = args["qm_indices"].split(",")
                is_list = True
            except:
                raise ValueError(
                    "Unable to parse EMLE_QM_INDICES environment variable as a comma-separated list of ints"
                )

    # A single entry list is assumed to be the path to a file.
    elif isinstance(args["qm_indices"], list):
        if len(args["qm_indices"]) == 1:
            args["qm_indices"] = args["qm_indices"][0]
        else:
            is_list = True

    # Try to parse a lists of QM indices into a list of ints.
    if is_list:
        try:
            args["qm_indices"] = [int(x) for x in args["qm_indices"]]
        except:
            raise TypeError("Unable to parse QM indices as a list of indices")

# Work out the DeePMD and OMNI-P2x models. We allow the following formatting:
#    1) A path to a single file.
#    2) Multiple files specified using wildcards.
#    3) A list of files, comma-separated.
#
# The first two can be found using glob, if empty then try splitting on ",".
for key, name in (("deepmd_model", "DeePMD"), ("omnip2x_model", "OMNI-P2x")):
    if args[key] is None:
        continue
    if isinstance(args[key], list) and len(args[key]) == 1:
        args[key] = args[key][0]
    if isinstance(args[key], str):
        # Remove whitespace.
        args[key] = args[key].replace(" ", "")

        # Try globbing.
        models = glob(args[key])

        # No matches.
        if not models:
            models = args[key].split(",")

            # Invalid formatting.
            if len(models) == 1:
                raise ValueError(
                    f"{name} model not found, or invalid formatting: '{args[key]}'"
                )
            else:
                args[key] = models
        else:
            args[key] = models

# Log errors by default.
if args["log_file"] is None:
    args["log_file"] = "emle_log.txt"

# Save settings by default.
if args["save_settings"] is None:
    args["save_settings"] = True

# Use the default backend if no backend is specified.
if args["backend"] is None:
    args["backend"] = "torchani"
# Convert single entries to strings.
elif len(args["backend"]) == 1:
    args["backend"] = args["backend"][0]

# Use the default backend if no external backend is specified.
if args["external_backend"] is None:
    if args["backend"] is None:
        args["backend"] = "torchani"
    print(f"Starting ML-MM server using {args['backend']} backend...")
else:
    print(f"Starting ML-MM server using external backend...")

# Create the EMLE socket.
sock = Socket()

try:
    sock.bind(host, port)
    sock.listen(num_clients)

    # Write the PID to file in the current directory.
    with open("emle_pid.txt", "w") as f:
        f.write(f"{os.getpid()}\n")

    # Write the port to file in the current directory.
    with open("emle_port.txt", "w") as f:
        f.write(f"{port}\n")
except:
    raise OSError(f"Server address already in use: ({host}, {port})") from None


# Import the EMLE calculator here so that we avoid the import overhead when the
# script is called to check if an existing server is running, e.g. when called
# as a background process by the orca executable.
from emle.calculator import EMLECalculator

# Initialise the EMLE calculator.
print("Initialising EMLE calculator...")
emle_calculator = EMLECalculator(**args)

while True:
    print("Waiting for a connection...")
    connection, client_address = sock.accept()
    try:
        print("Client connected:", client_address)
        while True:
            msg, path = connection.receive()
            if msg == "emlerun":
                # Try to run the EMLE calculation.
                print("Running EMLE calculation...")
                try:
                    emle_calculator.run(path=path)
                    msg = "7:emlefin"
                    print("Finished!")
                except Exception as e:
                    msg = f"emlefail:{str(e)}"
                    msg = f"{len(msg)}:{msg}"
                    print("Failed!")

                # Tell the client that we have finished.
                connection.send(msg, len(msg))
            elif msg == "emlelambda":
                # Try to update the interpolation lambda parameter.
                print("Updating interpolation lambda...")
                try:
                    emle_calculator.set_lambda_interpolate(float(path))
                    msg = "13:emlelambdaset"
                    print("Lambda set!")
                except Exception as e:
                    msg = f"emlefail:{str(e)}"
                    msg = f"{len(msg)}:{msg}"
                    print("Failed!")

                # Tell the client that we have finished.
                connection.send(msg, len(msg))
            else:
                break
    finally:
        connection.close()
