#!/usr/bin/env python3
"""
MT5 Position Monitor - 读取 EA 写入的 terminal_status.json
与 GoldAutoTradeBridgeEA 配合：一个 EA 同时负责交易执行和持仓数据回传
"""
import argparse, json, sys, time, pathlib

# EA 用 FILE_COMMON 写入，所以路径在 AppData/Roaming，不是 MQL5/Files
MT5_FILES  = pathlib.Path.home() / "Library/Application Support/net.metaquotes.wine.metatrader5/drive_c/users/user/AppData/Roaming/MetaQuotes/Terminal/Common/Files"
STATUS_FILE = MT5_FILES / "gold_autotrade/bridge/terminal_status.json"

def read_positions():
    """读取 terminal_status.json，返回持仓列表"""
    if not STATUS_FILE.exists():
        return None
    try:
        data = json.loads(STATUS_FILE.read_text())
        return data
    except (json.JSONDecodeError, KeyError):
        return None

def print_positions(data):
    if data is None:
        print("❌ terminal_status.json 不存在（EA 可能未加载或未编译）")
        return
    print(f"=== MT5 真实持仓 ===")
    print(f"更新时间: {data.get('updated', 'N/A')}")
    print(f"账户: {data.get('account', 'N/A')}")
    cnt = data.get("count", 0)
    print(f"XAUUSD 持仓数: {cnt}")

    positions = data.get("positions", [])
    if not positions:
        print("  (无持仓)")
    for pos in positions:
        print(f"  Ticket #{pos['ticket']}: {pos['side']} {pos['volume']}手 @{pos['entry']}")
        print(f"    SL={pos['sl']}  TP={pos['tp']}  PnL=${pos['pnl']}")

def get_state():
    """
    从 terminal_status.json 读取并转换为 agent_state 格式。
    如果无持仓返回 position_open=False。
    """
    data = read_positions()
    if data is None or data.get("count", 0) == 0:
        return {
            "position_open": False,
            "position_ticket": 0, "position_side": None,
            "position_entry": 0.0, "position_price": 0.0,
            "position_sl": 0.0, "position_tp": 0.0,
            "position_vol": 0.0,
        }

    pos = data["positions"][0]
    return {
        "position_open": True,
        "position_ticket": pos["ticket"],
        "position_side": pos["side"],
        "position_entry": pos["entry"],
        "position_price": pos["entry"],
        "position_sl": pos["sl"],
        "position_tp": pos["tp"],
        "position_vol": pos["volume"],
    }

def watch_positions(interval=5):
    """持续监控，报告变化"""
    last = None
    while True:
        data = read_positions()
        cur = data["count"] if data else -1
        ts = data.get("updated", "?") if data else "?"
        if cur != last:
            print(f"\n[{ts}] 持仓数变化: {last} → {cur}")
            print_positions(data)
            last = cur
        else:
            print(f"\r[{ts}] XAUUSD持仓: {cur}个", end="", flush=True)
        time.sleep(interval)

if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="MT5 Position Monitor")
    ap.add_argument("--watch", action="store_true", help="持续监控（每5秒）")
    ap.add_argument("--json", action="store_true", help="输出原始JSON")
    ap.add_argument("--interval", type=int, default=5, help="监控间隔秒数")
    args = ap.parse_args()

    if args.watch:
        print(f"监控 MT5 持仓（每 {args.interval}s，按 Ctrl+C 退出）...")
        try:
            watch_positions(args.interval)
        except KeyboardInterrupt:
            print("\n退出")
    else:
        data = read_positions()
        if args.json:
            print(json.dumps(data, indent=2))
        else:
            print_positions(data)
