"""合约 symbol 匹配(持仓 vs 监控/挂单)."""


def _symbol_base_coin(symbol: str) -> str:
    s = (symbol or "").strip().upper()
    if not s:
        return ""
    if "-SWAP" in s:
        s = s.replace("-SWAP", "")
    if "-" in s:
        return s.split("-", 1)[0]
    if "/" in s:
        return s.split("/", 1)[0]
    if ":" in s:
        return s.split(":", 1)[0]
    return s


def symbols_match(position_symbol: str, order_symbol: str) -> bool:
    a = (position_symbol or "").strip().upper()
    b = (order_symbol or "").strip().upper()
    if not a or not b:
        return False
    if a == b:
        return True
    ba, bb = _symbol_base_coin(a), _symbol_base_coin(b)
    if ba and bb and ba == bb:
        return True
    for suf in (":USDT", "/USDT:USDT", "/USDT"):
        a2 = a.replace(suf, "")
        b2 = b.replace(suf, "")
        if f"{a2}/USDT" == b or f"{a2}/USDT:USDT" == b:
            return True
        if f"{b2}/USDT" == a or f"{b2}/USDT:USDT" == a:
            return True
        if a2 == b2:
            return True
    return False
