#!/usr/bin/env python

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

import os
import sys
import time

from emle._socket import Socket

print("Starting EMLE client...")

# Check the number of command-line arguments.
if len(sys.argv) != 2:
    raise ValueError("usage: orca input_file")

# Get the ORCA input file name and validate.
orca_input = sys.argv[1]
if not os.path.isfile(orca_input):
    raise ValueError(f"Couldn't locate ORCA input file: {orca_input}")

# Create a socket and connect.
sock = Socket()

# See if the EMLE HOST, PORT, and RETRIES environment variables are set.
EMLE_HOST = os.getenv("EMLE_HOST")
try:
    EMLE_PORT = int(os.getenv("EMLE_PORT"))
except:
    EMLE_PORT = None
try:
    EMLE_RETRIES = int(os.getenv("EMLE_RETRIES"))
except:
    EMLE_RETRIES = None

# Fallback to default values.
if not EMLE_HOST:
    EMLE_HOST = "localhost"
if not EMLE_PORT:
    EMLE_PORT = 10000
if not EMLE_RETRIES:
    EMLE_RETRIES = 100

# 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, EMLE_RETRIES):
    try:
        print("Trying to establish a connection with the EMLE server...")
        sock.connect(EMLE_HOST, EMLE_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 {EMLE_HOST}:{EMLE_PORT} "
        "Please check that it is running."
    )

try:
    # Get the current working directory.
    cwd = os.getcwd()

    # Prepend the run message.
    msg = f"emlerun:{cwd}"

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

    print("Requesting EMLE calculation from server...")
    sock.send(msg, len(msg))

    msg, err = sock.receive()

    if msg == "emlefin":
        print("Received notice that the EMLE calculation has finished.")
        print("Dummy dipole for consistency with sander API when imin=6:")
        print("Total Dipole Moment    :      0.00000       0.00000       0.00000\n")
        print("Magnitude (a.u.)       :      0.00000")
    elif msg == "emlefail":
        print("Received notice that the EMLE calculation has failed.")
        print(f"[ERROR] {err}")
    else:
        raise RuntimeError(f"Invalid message received from EMLE server: '{msg}'")

finally:
    print("Closing client connection.")
    sock.close()
