#!/usr/bin/env python3
# File: bci_web_server.py
# Article 23193 - Overcoming Accessibility VI
# HTTP server that provides BCI commands via REST API
# Dependencies: pip install flask

from flask import Flask
import random
import threading
import time

app = Flask(__name__)

# Current command state
current_command = {"cmd": "HOLD", "value": 0.0}

COMMANDS = ['BUY', 'SELL', 'CLOSE', 'HOLD']
LOT_SIZES = [0.01, 0.05, 0.1]

def generate_commands():
    """Background thread that generates random BCI commands."""
    global current_command
    print("Command generator started. Sending commands every 2-5 seconds.")
    while True:
        cmd = random.choice(COMMANDS)
        value = random.choice(LOT_SIZES) if cmd in ['BUY', 'SELL'] else 0.0
        current_command = {"cmd": cmd, "value": value}
        print(f"  Generated: {cmd}:{value}")
        time.sleep(random.uniform(2.0, 5.0))

@app.route('/command', methods=['GET'])
def get_command():
    """Return the current BCI command and reset to HOLD."""
    global current_command
    cmd = current_command.copy()
    current_command = {"cmd": "HOLD", "value": 0.0}
    return cmd

@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint."""
    return {"status": "ok"}

@app.route('/direct/<cmd>', methods=['GET'])
def direct_command(cmd):
    """Direct command endpoint for testing."""
    cmd_upper = cmd.upper()
    if cmd_upper in ['BUY', 'SELL', 'CLOSE']:
        current_command = {"cmd": cmd_upper, "value": 0.1}
        return {"status": "sent", "cmd": cmd_upper}
    return {"status": "error", "message": "Unknown command"}, 400

if __name__ == '__main__':
    # Start the command generator in a background thread
    gen_thread = threading.Thread(target=generate_commands, daemon=True)
    gen_thread.start()
    
    print("=" * 50)
    print("BCI Web Server running on http://127.0.0.1:8080")
    print("Endpoints:")
    print("  GET /command  - Get latest BCI command")
    print("  GET /health   - Health check")
    print("  GET /direct/BUY  - Send direct BUY command")
    print("  GET /direct/SELL - Send direct SELL command")
    print("  GET /direct/CLOSE - Send direct CLOSE command")
    print("=" * 50)
    print("Make sure to add http://127.0.0.1:8080 to MT5 WebRequest allowed list!")
    print("Tools -> Options -> Expert Advisors -> Allow WebRequest")
    
    app.run(host='127.0.0.1', port=8080, debug=False, threaded=True)