import json
import websocket
import time
import os

# Configuration
API_URL = "wss://ws.binaryws.com/websockets/v3?app_id=YourAppID"
API_TOKEN = "you AP1 token"

# File paths
MQL5_TO_PYTHON = "C:/Users/YourCmputerName/AppData/Roaming/MetaQuotes/Terminal/Common/Files/mql5_to_python.txt"
PYTHON_TO_MQL5 = "C:/Users/YourComputerName/AppData/Roaming/MetaQuotes/Terminal/Common/Files/python_to_mql5.txt"

# WebSocket connection
ws = websocket.WebSocket()

def connect_to_deriv():
    """Connects to Deriv's WebSocket API."""
    try:
        ws.connect(API_URL)
        ws.send(json.dumps({"authorize": API_TOKEN}))
        response = json.loads(ws.recv())
        print(f"Authorization Response: {response}")
        if response.get("error"):
            print("Authorization failed:", response["error"]["message"])
            return False
        return True
    except Exception as e:
        print(f"Error during authorization: {e}")
        return False

def process_command(command):
    """Processes a command from MQL5."""
    try:
        command_data = json.loads(command)  # Parse the JSON command
        if "mt5_deposit" in command_data:
            return mt5_deposit(
                command_data["amount"],
                command_data["from_binary"],
                command_data["to_mt5"]
            )
        else:
            return {"error": "Unknown command"}
    except json.JSONDecodeError:
        return {"error": "Invalid command format"}
    except Exception as e:
        return {"error": f"Unexpected error: {e}"}

def mt5_deposit(amount, from_binary, to_mt5):
    """Performs a deposit operation to the MT5 account."""
    try:
        ws.send(json.dumps({
            "mt5_deposit": 1,
            "amount": amount,
            "from_binary": from_binary,
            "to_mt5": to_mt5
        }))
        response = ws.recv()
        return json.loads(response)
    except Exception as e:
        return {"error": f"Error during deposit operation: {e}"}

def read_command():
    """Reads a command from the MQL5 file and deletes the file after reading."""
    print(f"Checking for command file at: {MQL5_TO_PYTHON}")
    if os.path.exists(MQL5_TO_PYTHON):
        print(f"Command file found: {MQL5_TO_PYTHON}")
        with open(MQL5_TO_PYTHON, "r", encoding="utf-8") as file:
            command = file.read().strip()
        print(f"Raw Command read: {repr(command)}")
        
        # Strip potential BOM and whitespace
        if command.startswith("\ufeff"):
            command = command[1:]
        
        print(f"Processed Command: {repr(command)}")
        os.remove(MQL5_TO_PYTHON)  # Remove file after reading
        return command
    print(f"Command file not found at: {MQL5_TO_PYTHON}")
    return None

def write_response(response):
    """Writes a response to the MQL5 file."""
    with open(PYTHON_TO_MQL5, "w", encoding="utf-8") as file:
        file.write(json.dumps(response))

if __name__ == "__main__":
    if not connect_to_deriv():
        print("Failed to authorize. Exiting.")
        exit(1)

    print("Connected and authorized. Waiting for commands...")
    while True:
        try:
            command = read_command()
            if command:
                print(f"Processing command: {command}")
                response = process_command(command)
                print(f"Response: {response}")
                write_response(response)
                print("Response written. Exiting loop.")
                break  # Exit the loop after processing one command
            else:
                print("No command file found. Exiting.")
                break  # Exit the loop if the command file is not found
        except Exception as e:
            print(f"Error in main loop: {e}")
            break  # Exit the loop on unexpected error
