"""`python run.py check` : test the MT5 connection step by step, with plain-language fixes."""
from .data import mt5_candles


def run(cfg):
    from .mt5conn import get_mt5
    rows = []

    def add(name, ok, detail, fix=""):
        rows.append((name, ok, detail, fix))
        print(("PASS  " if ok else "FAIL  ") + f"{name}: {detail}" + (f"\n      -> {fix}" if (fix and not ok) else ""))
        return ok

    try:
        m = get_mt5()
    except Exception as e:
        add("Connect to MT5", False, str(e), "Open the MT5 app, log in to your demo account, then run this again.")
        return False
    add("Connect to MT5", True, "connected")
    ai = m.account_info()
    if ai is None:
        return add("Account", False, "no account logged in", "Log in inside MT5 (File > Login to Trade Account).")
    demo = ai.trade_mode == m.ACCOUNT_TRADE_MODE_DEMO
    add("Account", True, f"login {ai.login}, server {ai.server}, {'DEMO' if demo else 'REAL MONEY'}, "
                         f"balance {ai.balance:.2f} {ai.currency}, equity {ai.equity:.2f}")
    add("Demo account", demo or cfg["mode"] != "demo", "ok" if demo else "this is a REAL account",
        "Mode is 'demo', so Sailar-x will refuse to trade on a real account.")
    ti = m.terminal_info()
    add("Algo trading allowed", bool(ti and ti.trade_allowed), "on" if ti and ti.trade_allowed else "OFF",
        "In MT5 click the 'Algo Trading' button in the top toolbar so it turns green, and tick "
        "Tools > Options > Expert Advisors > 'Allow algorithmic trading'.")
    sym = cfg["symbol"]
    info = m.symbol_info(sym)
    if info is None:
        return add("Symbol", False, f"{sym} not found", "Use the exact name from Market Watch (some brokers add a suffix).")
    m.symbol_select(sym, True)
    add("Symbol", True, f"{sym}: lot {info.volume_min} to {info.volume_max}, step {info.volume_step}, contract {info.trade_contract_size}")
    t = m.symbol_info_tick(sym)
    add("Live price", t is not None and t.bid > 0, f"bid {t.bid} ask {t.ask}" if t else "none",
        "Market may be closed (forex closes on weekends).")
    try:
        df = mt5_candles(cfg, cfg["candles"])
        add("Candles", len(df) >= 300, f"{len(df)} candles of {cfg['primary_timeframe']}",
            "Scroll the chart back in MT5 or increase 'Max bars in chart' in Tools > Options > Charts.")
    except Exception as e:
        add("Candles", False, str(e))
    if t:
        c = m.order_calc_profit(m.ORDER_TYPE_BUY, sym, 1.0, t.ask, t.ask - 0.0010)
        mg = m.order_calc_margin(m.ORDER_TYPE_BUY, sym, 1.0, t.ask)
        add("Risk maths", c is not None and mg is not None,
            f"1 lot losing 10 pips = {abs(c):.2f}; margin for 1 lot = {mg:.2f}" if c is not None and mg is not None else "failed")
    ok = all(r[1] for r in rows)
    print("\nAll checks passed. Safe to try: python run.py run --config config.mt5.json" if ok
          else "\nFix the FAIL items above, then run the check again.")
    return ok
