# ftsaaipkg/cli.py

import os
import sys
import time
import requests
from pymongo import MongoClient
from dotenv import load_dotenv
from .bridge import connect_mt5, get_account_summary, get_open_trades

# Load environment variables
load_dotenv()

# Load Mongo URI from .env
MONGO_URI = os.getenv("MONGO_URI")
if not MONGO_URI:
    print("MONGO_URI not set in .env. Exiting...")
    sys.exit(1)

DB_NAME = "ftsa_ai"

BACKEND_URL = "https://ftsa-ai-backend.onrender.com/api/ftsaaicli/mt5trades"

# File to track live streaming status
RUN_FILE = os.path.join(os.path.expanduser("~"), "ftsaai_running.txt")


def get_user_by_email(email: str, client: MongoClient):
    db = client[DB_NAME]
    return db.users.find_one({"email": email.lower()})


def get_mt_accounts(user_id: str, client: MongoClient):
    db = client[DB_NAME]
    return list(db.mtaccounts.find({"userId": user_id}))


def get_prop_accounts(user_id: str, client: MongoClient):
    db = client[DB_NAME]
    return list(db.propaccounts.find({"userId": user_id}))


def run_cli():
    print("=== FTSA AI MT5 Connector ===")
    email = input("Enter your email: ").strip()

    client = MongoClient(MONGO_URI)

    try:
        # Create running flag
        with open(RUN_FILE, "w") as f:
            f.write("running")

        user = get_user_by_email(email, client)
        if not user:
            print(f"User with email '{email}' not found.")
            print("Existing users in the database:")
            for u in client[DB_NAME].users.find({}, {"email": 1}):
                print(" -", u["email"])
            sys.exit(1)

        user_id = str(user["_id"])
        print(f"Found user: {user.get('firstName', 'Unknown')} (ID: {user_id})")

        mt_accounts = get_mt_accounts(user_id, client)
        prop_accounts = get_prop_accounts(user_id, client)

        # Prefer MT account first, fallback to Prop
        account = mt_accounts[0] if mt_accounts else (
            prop_accounts[0] if prop_accounts else None
        )

        if not account:
            print("No MT or Prop accounts found for this user. Exiting...")
            sys.exit(1)

        broker = account.get("broker", "Unknown")
        login = account.get("login")
        password = account.get("password")
        server = account.get("server")

        if not all([login, password, server]):
            print("Account credentials are incomplete. Cannot connect to MT5.")
            sys.exit(1)

        print(f"Using account from broker: {broker}")
        print(f"Connecting to MT5 account {login} on {server}...")

        # CONNECT TO MT5
        if connect_mt5(login, password, server):
            print("MT5 connection established successfully!")
            print("Starting live trade streaming...\n")
        else:
            print("Failed to connect to MT5.")
            sys.exit(1)

        # 🔥 LIVE STREAM LOOP
        last_trades = None  # track last trades to send only if changed
        first_sync_done = False  # to print success message only once
        spinner_chars = ['|', '/', '-', '\\']  # spinner animation
        spinner_index = 0

        while True:
            try:
                # Stop if exit command deleted the flag
                if not os.path.exists(RUN_FILE):
                    print("\n🛑 Stop signal received. Exiting live streaming...")
                    break

                summary = get_account_summary()
                trades = get_open_trades()

                # Only send if trades have changed
                if trades != last_trades:
                    payload = {
                        "userId": user_id,
                        "broker": broker,
                        "login": int(login),
                        "summary": summary,
                        "trades": trades
                    }

                    try:
                        response = requests.post(BACKEND_URL, json=payload, timeout=10)
                        if response.status_code == 200 and not first_sync_done:
                            print("✅ Trades synced successfully")
                            first_sync_done = True
                        elif response.status_code != 200:
                            print(f"❌ Sync failed ({response.status_code})")
                    except Exception as e:
                        print(f"Error sending trades to backend: {e}")

                    last_trades = trades

                # Animate spinner for live streaming
                spinner_char = spinner_chars[spinner_index]
                spinner_index = (spinner_index + 1) % len(spinner_chars)
                print(f"\r🟢📈⚡ Live trades ongoing {spinner_char}   ", end='', flush=True)

                # Poll every 0.3 seconds for near real-time updates
                time.sleep(0.3)

            except KeyboardInterrupt:
                print("\nStopping live streaming...")
                break
            except Exception as e:
                print(f"\nError during streaming: {e}")
                time.sleep(0.3)

    finally:
        # Remove running flag on exit
        if os.path.exists(RUN_FILE):
            os.remove(RUN_FILE)
        client.close()


if __name__ == "__main__":
    run_cli()