from __future__ import annotations

from typing import Any


def normalize_language(language: str | None) -> str:
    if not language:
        return "zh"
    s = str(language).strip().lower()
    if s in ("en", "english"):
        return "en"
    return "zh"


def _block(title: str, lines: list[str]) -> str:
    return "\n".join([title, *lines])

def _mask_addr(addr: str) -> str:
    s = str(addr or "").strip()
    if len(s) <= 12:
        return s
    if s.startswith("0x") and len(s) >= 10:
        return s[:6] + "…" + s[-4:]
    return s[:4] + "…" + s[-4:]


def format_monitor_open_alert(
    *,
    lang: str,
    coin: str,
    is_short: bool,
    leverage_x: float | None,
    sz: float,
    entry_px: float,
    user: str,
    account_value_usd: float | None,
    pnl_24h_usd: float | None,
    unrealized_pnl_usd: float | None,
) -> str:
    """
    Monitor open-position alert (zh/en via lang).
    """

    language = normalize_language(lang)
    lev_text = (f"{int(leverage_x)}x" if leverage_x is not None and leverage_x > 0 else None)
    bal_text = (f"{account_value_usd:.4f} $" if account_value_usd is not None else "--")

    if pnl_24h_usd is None:
        pnl_24h_text_zh = "--"
        pnl_24h_text_en = "--"
    else:
        arrow_zh = "↑" if pnl_24h_usd >= 0 else "↓"
        arrow_en = "↑" if pnl_24h_usd >= 0 else "↓"
        pnl_24h_text_zh = f"{pnl_24h_usd:.4f} $ {arrow_zh}"
        pnl_24h_text_en = f"{pnl_24h_usd:.4f} $ {arrow_en}"

    if unrealized_pnl_usd is None:
        upnl_text_zh = "--"
        upnl_text_en = "--"
    else:
        upnl_text_zh = f"{unrealized_pnl_usd:.4f}  $ 📈" if unrealized_pnl_usd >= 0 else f"{unrealized_pnl_usd:.4f}  $ 📉"
        upnl_text_en = f"{unrealized_pnl_usd:.4f}  $ 📈" if unrealized_pnl_usd >= 0 else f"{unrealized_pnl_usd:.4f}  $ 📉"

    if language == "en":
        op = "Open (Short)" if bool(is_short) else "Open (Long)"
        lines = [
            "👀【Monitor Open Alert】👀",
            "",
            f"Coin: {coin}",
            f"Action: {op}",
        ]
        if lev_text:
            lines.append(f"Leverage: {lev_text}")
        lines.extend(
            [
                f"Size: {abs(float(sz))}",
                f"Entry Price: ${entry_px}",
                "",
                "👀️Monitored Address Info👇",
                f"├Address: {_mask_addr(user)}",
                f"├Account Value: {bal_text}",
                f"├24H PnL Change (incl. deposits): {pnl_24h_text_en}",
                f"└💰Total Unrealized PnL: {upnl_text_en}",
            ]
        )
        return "\n".join(lines)

    op = "开仓（空单）" if bool(is_short) else "开仓（多单）"
    lines_zh = [
        "👀【监控开仓提醒】👀",
        "",
        f"币种：{coin}",
        f"操作：{op}",
    ]
    if lev_text:
        lines_zh.append(f"杠杆：{lev_text}")
    lines_zh.extend(
        [
            f"数量：{abs(float(sz))}",
            f"开仓价格：${entry_px}",
            "",
            "👀️监控地址信息👇",
            f"├当前监控地址：{_mask_addr(user)}",
            f"├合约账户余额: {bal_text}",
            f"├24H盈亏变化(含充值): {pnl_24h_text_zh}",
            f"└💰总未实现盈亏：{upnl_text_zh}",
        ]
    )
    return "\n".join(lines_zh)


def format_monitor_close_alert(
    *,
    lang: str,
    coin: str,
    was_short: bool,
    leverage_x: float | None,
    sz: float,
    entry_px: float | None,
    value_usd: float | None,
    pnl_usd: float | None,
    user: str,
    account_value_usd: float | None,
    pnl_24h_usd: float | None,
    unrealized_pnl_usd: float | None,
) -> str:
    language = normalize_language(lang)
    op_zh = "平仓（空单）" if bool(was_short) else "平仓（多单）"
    op_en = "Close (Short)" if bool(was_short) else "Close (Long)"
    lev_text = (f"{int(leverage_x)}x" if leverage_x is not None and leverage_x > 0 else None)

    entry_text_zh = (f"${entry_px:.4f}" if entry_px is not None else "--")
    entry_text_en = (f"${entry_px:.4f}" if entry_px is not None else "--")
    value_text_zh = (f"${value_usd:.4f}" if value_usd is not None else "--")
    value_text_en = (f"${value_usd:.4f}" if value_usd is not None else "--")
    pnl_text_zh = (f"${pnl_usd:.4f}" if pnl_usd is not None else "--")
    pnl_text_en = (f"${pnl_usd:.4f}" if pnl_usd is not None else "--")

    bal_text = (f"{account_value_usd:.4f} $" if account_value_usd is not None else "--")

    if pnl_24h_usd is None:
        pnl_24h_text_zh = "--"
        pnl_24h_text_en = "--"
    else:
        arrow = "↑" if pnl_24h_usd >= 0 else "↓"
        pnl_24h_text_zh = f"{pnl_24h_usd:.4f} $ {arrow}"
        pnl_24h_text_en = f"{pnl_24h_usd:.4f} $ {arrow}"

    if unrealized_pnl_usd is None:
        upnl_text_zh = "--"
        upnl_text_en = "--"
    else:
        upnl_text_zh = f"{unrealized_pnl_usd:.4f}  $ 📈" if unrealized_pnl_usd >= 0 else f"{unrealized_pnl_usd:.4f}  $ 📉"
        upnl_text_en = f"{unrealized_pnl_usd:.4f}  $ 📈" if unrealized_pnl_usd >= 0 else f"{unrealized_pnl_usd:.4f}  $ 📉"

    if language == "en":
        lines = [
            "👀【Monitor Close Alert】👀",
            "",
            f"Coin: {coin}",
            f"Action: {op_en}",
        ]
        if lev_text:
            lines.append(f"Leverage: {lev_text}")
        lines.extend(
            [
                f"Size: {abs(float(sz))}",
                f"Entry Price: {entry_text_en}",
                f"Value: {value_text_en}",
                f"PnL: {pnl_text_en}",
                "",
                "👀️Monitored Address Info👇",
                f"├Address: {_mask_addr(user)}",
                f"├Account Value: {bal_text}",
                f"├24H PnL Change (incl. deposits): {pnl_24h_text_en}",
                f"└💰Total Unrealized PnL: {upnl_text_en}",
            ]
        )
        return "\n".join(lines)

    lines_zh = [
        "👀【监控平仓提醒】👀",
        "",
        f"币种：{coin}",
        f"操作：{op_zh}",
    ]
    if lev_text:
        lines_zh.append(f"杠杆：{lev_text}")
    lines_zh.extend(
        [
            f"数量：{abs(float(sz))}",
            f"开仓价格：{entry_text_zh}",
            f"价值：{value_text_zh}",
            f"盈亏：{pnl_text_zh}",
            "",
            "👀️监控地址信息👇",
            f"├当前监控地址：{_mask_addr(user)}",
            f"├合约账户余额: {bal_text}",
            f"├24H盈亏变化(含充值): {pnl_24h_text_zh}",
            f"└💰总未实现盈亏：{upnl_text_zh}",
        ]
    )
    return "\n".join(lines_zh)


def format_copy_liquidation_warning(
    *,
    lang: str,
    coin: str,
    dex: str,
    remaining_pct: float,
    threshold_pct: float,
) -> str:
    """
    Liquidation distance warning (copy module).
    `remaining_pct`: distance to liquidation (percent)
    `threshold_pct`: triggered threshold (percent)
    """

    language = normalize_language(lang)
    coin_s = str(coin)
    dex_s = str(dex or "")

    # risk level by threshold
    if float(threshold_pct) <= 1.0:
        level_zh = "极危"
        level_en = "Critical"
        suggest_zh = ["立即追加保证金", "或减仓降低杠杆"]
        suggest_en = ["Add margin immediately", "Or reduce position to lower leverage"]
    elif float(threshold_pct) <= 5.0:
        level_zh = "高危"
        level_en = "High"
        suggest_zh = ["立即追加保证金", "或减仓降低杠杆"]
        suggest_en = ["Add margin now", "Or reduce position to lower leverage"]
    else:
        level_zh = "中等"
        level_en = "Medium"
        suggest_zh = ["尽快追加保证金", "或减仓降低杠杆"]
        suggest_en = ["Consider adding margin", "Or reduce position to lower leverage"]

    if language == "en":
        return "\n".join(
            [
                "🚨 [Liquidation Warning | Risk System]",
                "",
                "📊 Account Type: Copy Trading",
                f"💱 Pair: {coin_s} ({dex_s or 'default'})",
                f"🏦 DEX: {dex_s or 'default'}",
                "",
                f"⚠️ Current Risk: Only {float(remaining_pct):.2f}% to liquidation (threshold ≤ {float(threshold_pct):.0f}%)",
                f"📉 Risk Level: {level_en}",
                "",
                "💡 Suggested Actions:",
                *[f"• {s}" for s in suggest_en],
                "",
                "⏰ Please act ASAP to avoid forced liquidation!",
            ]
        )

    return "\n".join(
        [
            "🚨 [清算预警 | 风控系统]",
            "",
            "📊 账户类型：Copy Trading",
            f"💱 交易对：{coin_s} ({dex_s or 'default'})",
            f"🏦 DEX：{dex_s or 'default'}",
            "",
            f"⚠️ 当前风险：距离清算仅剩 {float(remaining_pct):.2f}% （阈值 ≤ {float(threshold_pct):.0f}%）",
            f"📉 风险等级：{level_zh}",
            "",
            "💡 建议操作：",
            *[f"• {s}" for s in suggest_zh],
            "",
            "⏰ 请尽快处理，避免强制平仓！",
        ]
    )


def format_copy_tp_sl_trigger(
    *,
    lang: str,
    hit_tp: bool,
    coin: str,
    dex: str,
    pct: float,
    entry_px: float,
    mid: float,
) -> str:
    """
    Risk control signal message when TP/SL condition is triggered.
    """

    language = normalize_language(lang)
    typ_en = "Take Profit" if bool(hit_tp) else "Stop Loss"
    typ_zh = "止盈" if bool(hit_tp) else "止损"
    coin_s = str(coin)
    dex_s = str(dex or "")

    if language == "en":
        return "\n".join(
            [
                "📡 Trade Signal Triggered",
                "",
                f"Type: {typ_en}",
                f"Pair: {coin_s}",
                f"DEX: {dex_s}",
                "",
                f"PnL: {float(pct):.4f}%",
                f"Entry: {entry_px}",
                f"Mark: {mid}",
                "",
                "⚠️ Risk control executed",
            ]
        )

    return "\n".join(
        [
            "📡 触发交易信号",
            "",
            f"类型：{typ_zh}",
            f"交易对：{coin_s}",
            f"DEX：{dex_s}",
            "",
            f"盈亏：{float(pct):.4f}%",
            f"入场：{entry_px}",
            f"现价：{mid}",
            "",
            "⚠️ 已执行风控操作",
        ]
    )


def format_copy_started_status(
    *,
    lang: str,
    leader: str,
    scale: float,
    max_notional_usd: float | None,
    max_leverage: float | None,
    allowed_coins: list[str] | None,
    take_profit_pct: float | None,
    stop_loss_pct: float | None,
) -> str:
    language = normalize_language(lang)
    allowed_text = ",".join([str(x).strip() for x in (allowed_coins or []) if str(x).strip()]) or "ALL"

    if language == "en":
        tp_str = (f"{take_profit_pct}%" if take_profit_pct is not None else "OFF")
        sl_str = (f"{stop_loss_pct}%" if stop_loss_pct is not None else "OFF")
        return "\n".join(
            [
                "🚀 Copytrade Started",
                "",
                f"👤 Leader: {leader}",
                "",
                f"⚖️ Scale: {scale}",
                f"🧱 Max Notional: {max_notional_usd}",
                f"🧨 Max Leverage: {max_leverage}",
                f"🪙 Allowed Coins: {allowed_text}",
                "",
                f"🎯 Take Profit: {tp_str}",
                f"🛑 Stop Loss: {sl_str}",
            ]
        )

    tp_str = (f"{take_profit_pct}%" if take_profit_pct is not None else "关闭")
    sl_str = (f"{stop_loss_pct}%" if stop_loss_pct is not None else "关闭")
    return "\n".join(
        [
            "🚀 跟单已启动",
            "",
            f"👤 跟随者：{leader}",
            "",
            f"⚖️ 规模系数：{scale}",
            f"🧱 最大名义：{max_notional_usd}",
            f"🧨 最大杠杆：{max_leverage}",
            f"🪙 允许币种：{allowed_text}",
            "",
            f"🎯 止盈：{tp_str}",
            f"🛑 止损：{sl_str}",
        ]
    )


def format_copy_leader_liquidation_alert(
    *,
    lang: str,
    leader: str,
    pair: str,
    dex: str,
    balance_usdc: float | None,
    sz: float | None,
    liquidation_px: float | None,
    pnl_usd: float | None,
) -> str:
    """
    Leader liquidation alert (copy module).
    """

    language = normalize_language(lang)
    leader_full = str(leader)
    leader_masked = _mask_addr(leader_full)
    pair_s = str(pair)
    dex_s = str(dex or "")

    bal_usdc_text = (f"{balance_usdc:.2f} USDC" if balance_usdc is not None else "-- USDC")
    bal_line_zh = f"💰 余额  {bal_usdc_text}"
    bal_line_en = f"💰 Balance: {bal_usdc_text}"

    sz_text = (f"{abs(float(sz)):.4f}" if sz is not None else "--")
    liq_text = (f"${float(liquidation_px):.4f}" if liquidation_px is not None else "--")
    pnl_text = (f"${float(pnl_usd):.4f}" if pnl_usd is not None else "--")

    if language == "en":
        return "\n".join(
            [
                "⚠️【Leader Liquidation Alert】⚠️",
                "",
                f"The leader you follow ({leader_masked}) has been liquidated. Please review immediately.",
                "",
                "👥 Copy Account Info👇",
                bal_line_en,
                "",
                "📋 Leader Position Info👇",
                f"{pair_s} position has been liquidated!",
                f"Size: {sz_text}",
                f"Liquidation Price: {liq_text}",
                f"PnL: {pnl_text}",
                f"Leader: {leader_full}",
                f"DEX: {dex_s}",
            ]
        )

    return "\n".join(
        [
            "⚠️【跟单地址爆仓警报】⚠️",
            "",
            f"您跟随的地址{leader_masked}，{pair_s} 仓位已被强平，请注意查看",
            "",
            "👥 跟单账户信息👇",
            bal_line_zh,
            "",
            "📋「正在跟单地址」信息👇",
            f"{pair_s} 仓位已触发强平！",
            f"数量: {sz_text}",
            f"强平价格: {liq_text}",
            f"盈亏: {pnl_text}",
            f"正在跟单地址: {leader_full}",
            f"DEX: {dex_s}",
        ]
    )


def format_copy_open_alert(
    *,
    lang: str,
    coin: str,
    is_buy: bool,
    leverage_x: float | None,
    sz: float,
    entry_px: float,
    leader: str,
    balance_usdc: float | None,
) -> str:
    language = normalize_language(lang)
    lev_text = (f"{int(leverage_x)}x" if leverage_x is not None and leverage_x > 0 else "--")
    bal_usdc_text = (f"{balance_usdc:.2f} USDC" if balance_usdc is not None else "-- USDC")

    if language == "en":
        op = "Open (Long)" if bool(is_buy) else "Open (Short)"
        return "\n".join(
            [
                "✅📈 Copytrade Open Alert",
                "",
                f"Coin: {coin}",
                f"Action: {op}",
                f"Leverage: {lev_text}",
                f"Size: {abs(float(sz))}",
                f"Entry Price: ${entry_px}",
                "",
                "👤 Your Account",
                f"📋 Following: {leader}",
                f"💰 Balance: {bal_usdc_text}",
            ]
        )

    op = "开仓（多单）" if bool(is_buy) else "开仓（空单）"
    return "\n".join(
        [
            "✅📈 跟单开仓提醒👇",
            "",
            f"币种：{coin}",
            f"操作：{op}",
            f"杠杆： {lev_text}",
            f"数量： {abs(float(sz))}",
            f"开仓价格： ${entry_px}",
            "",
            "👤 你的账户信息👇",
            f"📋 正在跟单：{leader}",
            f"💰 余额  {bal_usdc_text}",
        ]
    )

def format_copy_close_alert(
    *,
    lang: str,
    coin: str,
    was_long: bool,
    sz: float,
    entry_px: float | None,
    position_notional: float | None,
    pnl_usd: float | None,
    leader: str,
    balance_usdc: float | None,
) -> str:
    language = normalize_language(lang)
    op_en = "Close (Long)" if bool(was_long) else "Close (Short)"
    op_zh = "平仓（多单）" if bool(was_long) else "平仓（空单）"

    entry_text = (f"${entry_px}" if entry_px is not None else "--")
    pos_text = (f"{position_notional:.4f}" if position_notional is not None else "--")
    pnl_text = (f"${pnl_usd:.4f}" if pnl_usd is not None else "--")
    bal_usdc_text = (f"{balance_usdc:.2f} USDC" if balance_usdc is not None else "-- USDC")
    if language == "en":
        return "\n".join(
            [
                "🔒📉 Copytrade Close Alert",
                "",
                f"Coin: {coin}",
                f"Action: {op_en}",
                f"Size: {abs(float(sz))}",
                f"Entry Price: {entry_text}",
                f"Position: {pos_text}",
                f"PnL: {pnl_text}",
                "",
                "👤 Your Account",
                f"📋 Following: {leader}",
                f"💰 Balance: {bal_usdc_text}",
            ]
        )

    entry_text_zh = (f"$%s" % (entry_px,) if entry_px is not None else "--")
    pnl_text_zh = (f"$%0.4f" % (pnl_usd,) if pnl_usd is not None else "--")
    return "\n".join(
        [
            "🔒📉 跟单平仓提醒👇",
            "",
            f"币种：{coin}",
            f"操作：{op_zh}",
            f"数量： {abs(float(sz))}",
            f"开仓价格： {entry_text_zh}",
            f"仓位： {pos_text}",
            f"盈亏： {pnl_text_zh}",
            "",
            "👤 你的账户信息👇",
            f"📋 正在跟单：{leader}",
            f"💰 余额  {bal_usdc_text}",
        ]
    )


def format_copy_min_notional_skip_alert(
    *,
    lang: str,
    leader: str,
    coin: str,
    min_notional_usd: float,
    balance_usdc: float | None,
) -> str:
    """
    Alert when copytrade cannot execute because planned notional is below exchange minimum.
    """

    language = normalize_language(lang)
    leader_masked = _mask_addr(str(leader))
    coin_s = str(coin)
    bal_text = (f"{balance_usdc:.2f} USDC" if balance_usdc is not None else "-- USDC")
    min_text = f"{float(min_notional_usd):.0f} USDC"

    if language == "en":
        return "\n".join(
            [
                "🚫🚫🚫 Copytrade Failed Alert! 🚫🚫🚫",
                "",
                f"💵 💥 Following leader {leader_masked} 🔥 opened a position!",
                "",
                f"⚠️⚠️ Your account does not meet the minimum open notional requirement ({min_text}). "
                "This copy action was skipped. Please top up your account. ⚠️⚠️",
                "",
                "👤 Your Account",
                f"💸 Available Balance: {bal_text}",
                f"🪙 Coin: {coin_s}",
            ]
        )

    return "\n".join(
        [
            "🚫🚫🚫 跟单失败提醒！🚫🚫🚫",
            "",
            f"💵 💥 正在跟单地址 {leader_masked} 🔥 开仓了!",
            "",
            f"⚠️⚠️ 由于您的账户当前可用余额不足 {min_text} 的最低开仓要求，无法执行本次跟单，请充值! ⚠️⚠️",
            "",
            "👤 你的账户信息👇",
            f"💸 可用跟单余额  {bal_text}",
            f"🪙 币种：{coin_s}",
        ]
    )


def format_copy_max_notional_skip_alert(
    *,
    lang: str,
    leader: str,
    coin: str,
    max_notional_usd: float,
    balance_usdc: float | None,
) -> str:
    """
    Alert when copytrade cannot execute because planned notional exceeds user's max_notional_usd.
    """

    language = normalize_language(lang)
    leader_masked = _mask_addr(str(leader))
    coin_s = str(coin)
    bal_text = (f"{balance_usdc:.2f} USDC" if balance_usdc is not None else "-- USDC")
    max_text = f"{float(max_notional_usd):.2f} USDC"

    if language == "en":
        return "\n".join(
            [
                "🚫🚫🚫 Copytrade Failed Alert! 🚫🚫🚫",
                "",
                f"💵 💥 Following leader {leader_masked} 🔥 opened a position!",
                "",
                f"⚠️⚠️ This copy action was skipped because it exceeds your max notional limit ({max_text}). "
                "Please adjust your risk settings if needed. ⚠️⚠️",
                "",
                "👤 Your Account",
                f"💸 Available Balance: {bal_text}",
                f"🪙 Coin: {coin_s}",
            ]
        )

    return "\n".join(
        [
            "🚫🚫🚫 跟单失败提醒！🚫🚫🚫",
            "",
            f"💵 💥 正在跟单地址 {leader_masked} 🔥 开仓了!",
            "",
            f"⚠️⚠️ 由于本次跟单名义金额超过你设置的最大名义限制（{max_text}），已跳过本次跟单。"
            "如需跟随请调整风控参数。⚠️⚠️",
            "",
            "👤 你的账户信息👇",
            f"💸 可用跟单余额  {bal_text}",
            f"🪙 币种：{coin_s}",
        ]
    )


def format_copy_exec_error_message(*, language: str, coin: str, leader: str, err: Any) -> str:
    if language == "en":
        title = "[copy][EXEC][ERROR]"
        return _block(title, [f"coin: {coin}", f"leader: {leader}", f"err: {err}"])
    return _block("[copy][执行][错误]", [f"币种: {coin}", f"跟随者: {leader}", f"错误: {err}"])


def format_monitor_user_event_message(*, language: str, user: str, kind: str) -> str:
    if language == "en":
        return _block("[monitor][USER_EVENT]", [f"user: {user}", f"kind: {kind}"])
    return _block("[monitor][用户事件]", [f"用户: {user}", f"类型: {kind}"])


def format_monitor_ledger_message(
    *,
    language: str,
    action: str,
    amount_usdc: float,
    type_name: str,
    src_user: str,
    destination: str,
    time_ms: Any,
) -> str:
    if language == "en":
        return _block(
            "👀【Monitor Balance Change Alert】👀",
            [
                f"action: {action}",
                f"amount_usdc: {amount_usdc:.6f} USDC",
                f"type: {type_name}",
                f"src_user: {src_user}",
                f"destination: {destination}",
                f"time_ms: {time_ms}",
            ],
        )

    zh_action = {"deposit": "入金", "withdraw": "出金"}.get(action, action)
    return _block(
        "👀【监控资金变动提醒】👀",
        [
            f"动作: {zh_action}",
            f"金额(USDC): {amount_usdc:.6f}",
            f"类型: {type_name}",
            f"来源用户: {src_user}",
            f"目标用户: {destination}",
            f"时间(ms): {time_ms}",
        ],
    )


def format_common_status(language: str, msg: str) -> str:
    if language == "en":
        return f"[status] {msg}"
    return f"[状态] {msg}"

