from __future__ import annotations

import logging

logger = logging.getLogger(__name__)


def _notify_watchdog_trigger(
    stale_seconds: float,
    trades_received: int,
    restart_count: int,
) -> None:
    """Send Telegram alert when watchdog detects stale trade flow."""
    try:
        from opendeviationbar.notify.telegram import _build_context_block, send_telegram
    except ImportError:
        logger.warning("telegram module not available, skipping watchdog notification")
        return

    try:
        msg = (
            "<b>WATCHDOG TRIGGER</b>\n"
            f"<b>Stale:</b> {stale_seconds:.0f}s (no trade increment)\n"
            f"<b>Total trades:</b> {trades_received:,}\n"
            f"<b>Restart:</b> #{restart_count + 1}\n"
            "<b>Likely cause:</b> WS silently disconnected or exchange maintenance\n"
            "<b>Next:</b> Sidecar will restart engine + gap-fill from last known trade"
            + _build_context_block("sidecar")
        )
        send_telegram(msg, disable_notification=False)
    except Exception:
        logger.exception("failed to send watchdog Telegram notification")


def _notify_lethe_overflow(new_drops: int, total_drops: int) -> None:
    """Lethe: alert when ring buffer drops bars (silent data loss)."""
    try:
        from opendeviationbar.notify.telegram import _build_context_block, send_telegram
    except ImportError:
        return
    try:
        msg = (
            "<b>LETHE: RING BUFFER OVERFLOW</b>\n"
            f"<b>New drops:</b> {new_drops:,}\n"
            f"<b>Total drops:</b> {total_drops:,}\n"
            "<b>Cause:</b> Backpressure from slow ClickHouse writes\n"
            "<b>Impact:</b> Bars lost until kintsugi reconciles\n"
            "<b>If recurring:</b> Check CH write latency or increase buffer size"
            + _build_context_block("sidecar")
        )
        send_telegram(msg, disable_notification=False)
    except Exception:
        logger.exception("Lethe: failed to send overflow alert")


def _notify_argus_stale(stale_symbols: list[str], timeout_s: int) -> None:
    """Argus: alert when symbols go silent beyond timeout."""
    try:
        from opendeviationbar.notify.telegram import _build_context_block, send_telegram
    except ImportError:
        return
    try:
        symbols_str = ", ".join(sorted(stale_symbols))
        msg = (
            "<b>ARGUS: SYMBOL SILENCE</b>\n"
            f"<b>Symbols:</b> {symbols_str}\n"
            f"<b>Silent for:</b> &gt;{timeout_s}s\n"
            "<b>Possible causes:</b> (1) WS feed dropped for subset, "
            "(2) exchange delisted symbol, (3) extreme low volume period\n"
            "<b>Check:</b> WebSocket connectivity, exchange status"
            + _build_context_block("sidecar")
        )
        send_telegram(msg, disable_notification=False)
    except Exception:
        logger.exception("Argus: failed to send stale symbol alert")


def _notify_charon_replay(bars_replayed: int, trigger: str) -> None:
    """Charon: informational alert when dead-letter bars are replayed."""
    try:
        from opendeviationbar.notify.telegram import _build_context_block, send_telegram
    except ImportError:
        return
    try:
        msg = (
            "<b>CHARON: DEAD-LETTER REPLAY</b>\n"
            f"<b>Bars replayed:</b> {bars_replayed:,}\n"
            f"<b>Trigger:</b> {trigger}\n"
            "<b>Context:</b> Bars were dead-lettered due to prior CH write failures. "
            "Replay succeeded — data integrity restored."
            + _build_context_block("sidecar")
        )
        send_telegram(msg, disable_notification=True)
    except Exception:
        logger.exception("Charon: failed to send replay notification")


def _notify_restart_failure(
    restart_number: int,
    consecutive_timeouts: int,
    stale_seconds: float,
) -> None:
    """Alert ops when watchdog restart fails via Telegram."""
    try:
        from opendeviationbar.notify.telegram import _build_context_block, send_telegram
    except ImportError:
        logger.warning("telegram module not available for restart failure alert")
        return

    try:
        msg = (
            "<b>WATCHDOG RESTART FAILED</b>\n"
            f"<b>Attempt:</b> {restart_number}\n"
            f"<b>Consecutive timeouts:</b> {consecutive_timeouts}\n"
            f"<b>Stale:</b> {stale_seconds:.0f}s\n"
            "<b>Action:</b> Sidecar will exit. systemd should auto-restart.\n"
            "<b>Check:</b> <code>journalctl --user "
            "-u opendeviationbar-sidecar -n 50</code>" + _build_context_block("sidecar")
        )
        send_telegram(msg, disable_notification=False)
        logger.info("restart failure alert sent via Telegram")
    except Exception:
        logger.exception("failed to send restart failure alert")
