import time
import os
import sys
import signal
import threading
import warnings
import json

# Suppress pandas FutureWarnings
warnings.filterwarnings('ignore', category=FutureWarning)

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import lib
import MetaTrader5 as mt5
mt5.initialize()

# Use data_storage for proper path handling
try:
    from data_storage import get_config_file_path
    STOP_FLAG_FILE = get_config_file_path('.bots_stop')
    SETTINGS_FILE = get_config_file_path('settings.json')
except:
    APP_ROOT = os.path.dirname(os.path.dirname(__file__))
    STOP_FLAG_FILE = os.path.join(APP_ROOT, '.bots_stop')
    SETTINGS_FILE = os.path.join(APP_ROOT, 'settings.json')

print("🤖 SuperTrend Bot STARTED")

# User settings (will be overwritten by settings.json)
symbol = 'XAUUSD'
tf = '3m'
daily_drawdown = 100.0
atr_multiplier = 3.0
atr_period = 11
lot = 0.01

def should_stop():
    return os.path.exists(STOP_FLAG_FILE)

def signal_handler(sig, frame):
    sys.exit(0)

# Only register signal handlers if running in main thread
if threading.current_thread() is threading.main_thread():
    try:
        signal.signal(signal.SIGTERM, signal_handler)
        signal.signal(signal.SIGINT, signal_handler)
    except:
        pass

# Load settings from JSON
def load_settings():
    try:
        if os.path.exists(SETTINGS_FILE):
            with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
    except:
        pass
    return {}

risk_or_lot = 'LOT'
value = 0.01
daily_tp_target = 2
news = False
todayBLC = mt5.account_info().balance

# User settings
atr_period = 10
multiplier = 2

last_reload = 0
reload_interval = 5  # Reload settings every 5 seconds

while True:
    if should_stop():
        print("🛑 SuperTrend Bot stopping...")
        break
    
    # Reload settings every 5 seconds
    current_time = time.time()
    if current_time - last_reload > reload_interval:
        try:
            settings = load_settings()
            symbol = settings.get('symbol', symbol)
            tf = settings.get('timeframe', tf)
            daily_drawdown = float(settings.get('daily_drawdown_pct', daily_drawdown))
            risk_or_lot = settings.get('volume_type', risk_or_lot)
            value = float(settings.get('volume_amount', value))
            daily_tp_target = int(settings.get('daily_tp_count', daily_tp_target))
            news = settings.get('news_filter', news)
            last_reload = current_time
        except:
            pass
    
    try:
        super_var = True
        if lib.daily_draw_down_checker(todayBLC, daily_drawdown):
            super_var = False
        
        if lib.count_tp() >= daily_tp_target:
            super_var = False

        # ✅ بررسی فقط positions مال این ربات (با comment 'superTrend_var')
        positions = mt5.positions_get()
        for pos in positions:
            if pos.comment == 'superTrend_var':
                super_var = False
                break
        
        st = lib.supertrend(symbol, tf, atr_period, multiplier)
        price = mt5.symbol_info_tick(symbol)
        
        signal = lib.Trend_change_signal(st['position'])
        if super_var == True and signal == 'buy':
            sl = st['value'][-2]
            tp = price.ask + ((price.ask - sl) * 3)
            
            if risk_or_lot == "LOT":
                lot = value
            else:
                lot = lib.lot_calculator(symbol, value, price.ask, sl)
            lib.create_order(symbol, lot, lib.buy, sl, tp, 'superTrend_var')
            super_var = False
            
        if super_var == True and signal == 'sell':
            sl = st['value'][-2]
            tp = price.bid - ((sl - price.bid) * 3)
            
            if risk_or_lot == "LOT":
                lot = value
            else:
                lot = lib.lot_calculator(symbol, value, price.bid, sl)
            lib.create_order(symbol, lot, lib.sell, sl, tp, 'superTrend_var')
            super_var = False
        
        time.sleep(5)
            
    except Exception as e:
        print(f"Error: {e}")
        time.sleep(1)  # Changed from 10 to 1 second
        continue  # Check stop flag sooner
    
    # Check stop flag frequently
    if should_stop():
        print("🛑 SuperTrend Bot stopping...")
        break

print("🛑 SuperTrend Bot STOPPED")
sys.exit(0)
