from __future__ import annotations

import logging

from app.models.telegram_schemas import (
    TelegramAlertSeverity,
    TelegramAlertType,
    TelegramResponse,
)

logger = logging.getLogger("dscons.telegram.alerts")


class TelegramAlertsMixin:
    """Alert and notification dispatching logic."""

    async def send_alert(
        self,
        title: str,
        alert_type: TelegramAlertType = TelegramAlertType.SYSTEM_NOTIFICATION,
        severity: TelegramAlertSeverity = TelegramAlertSeverity.INFO,
        project_name: str | None = None,
        details: list[str] | None = None,
        action_url: str | None = None,
        chat_id: str | None = None,
    ) -> TelegramResponse:
        """Format and send a structured enterprise alert card."""
        severity_icons = {
            TelegramAlertSeverity.CRITICAL: "🚨 <b>[CẢNH BÁO KHẨN CẤP]</b>",
            TelegramAlertSeverity.WARNING: "⚠️ <b>[CẢNH BÁO VẬN HÀNH]</b>",
            TelegramAlertSeverity.SUCCESS: "✅ <b>[THÀNH CÔNG]</b>",
            TelegramAlertSeverity.INFO: "ℹ️ <b>[THÔNG BÁO]</b>",
        }
        icon_hdr = severity_icons.get(severity, "ℹ️ <b>[THÔNG BÁO]</b>")

        lines = [
            f"{icon_hdr} <b>{title}</b>",
            f"<b>Phân Hệ:</b> <code>{alert_type.value}</code>",
        ]
        if project_name:
            lines.append(f"<b>Dự Án:</b> <code>{project_name}</code>")

        if details:
            lines.append("<b>Chi Tiết:</b>")
            for item in details:
                lines.append(f" • {item}")

        if action_url:
            lines.append(
                f"\n🔗 <a href='{action_url}'>Xem chi tiết trên ERP DSCons</a>"
            )

        lines.append("<i>— ĐỊNH SƠN ERP Enterprise AEC System —</i>")
        msg_text = "\n".join(lines)
        return await self.send_message(msg_text, chat_id=chat_id)
