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 "--")
    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)"
        return "\n".join(
            [
                "👀【Monitor Open Alert】👀",
                "",
                f"Coin: {coin}",
                f"Action: {op}",
                f"Leverage: {lev_text}",
                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}",
            ]
        )

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


def format_monitor_close_alert(
    *,
    lang: str,
    coin: str,
    was_short: bool,
    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)"

    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":
        return "\n".join(
            [
                "👀【Monitor Close Alert】👀",
                "",
                f"Coin: {coin}",
                f"Action: {op_en}",
                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(
        [
            "👀【监控平仓提醒】👀",
            "",
            f"币种：{coin}",
            f"操作：{op_zh}",
            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}",
        ]
    )


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_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}"

