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

# EA 用 FILE_COMMON 写入，所以路径在 AppData/Roaming，不是 MQL5/Files
if sys.platform == "win32":
    MT5_FILES  = pathlib.Path(os.environ["APPDATA"]) / "MetaQuotes" / "Terminal" / "Common" / "Files"
else:
    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(encoding="utf-8"))
        return data
    except (json.JSONDecodeError, KeyError):
        return None

def print_positions(data):
    if data is None:
        print("[FAIL] 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,
        }

    positions = data.get("positions", [])
    if not isinstance(positions, list) or not positions:
        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 = positions[0]
    return {
        "position_open": True,
        "position_ticket": pos.get("ticket", 0),
        "position_side": pos.get("side"),
        "position_entry": pos.get("entry", 0.0),
        "position_price": pos.get("entry", 0.0),
        "position_sl": pos.get("sl", 0.0),
        "position_tp": pos.get("tp", 0.0),
        "position_vol": pos.get("volume", 0.0),
    }

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)
