"""Durable notification templates for Sentinel alarms."""
from __future__ import annotations

import re
from datetime import datetime


class NotificationTemplateEngine:
    """Build professional alarm messages from alarm context."""

    METRIC_LABELS = {
        "internal_temperature_c": ("Internal temperature", "°C"),
        "compressor_temperature_c": ("Compressor temperature", "°C"),
        "ambient_temperature_c": ("Ambient temperature", "°C"),
        "evaporator_temperature_c": ("Evaporator temperature", "°C"),
        "compressor_current_a": ("Compressor current", "A"),
        "health_score": ("Equipment Health", "/100"),
    }

    def build(self, row: dict[str, object], rule: dict[str, object] | None = None) -> tuple[str, str]:
        equipment_id = str(row.get("equipment_id") or "Unknown equipment")
        severity = str(row.get("severity") or "ALARM").upper()
        title = str(row.get("title") or "Sentinel alarm")
        opened_at = str(row.get("opened_at") or "")
        metric, value, comparator, threshold = self._parse_message(str(row.get("message") or ""))
        label, unit = self.METRIC_LABELS.get(metric, (metric.replace("_", " ").title() if metric else "Measured value", ""))
        duration = self._duration(opened_at)
        subject = f"[{severity}] Sentinel Cold — {equipment_id} — {title}"
        lines = [
            "Sentinel Cold Alarm",
            "",
            f"Equipment: {equipment_id}",
            f"Alarm: {title}",
            f"Severity: {severity}",
        ]
        if opened_at:
            lines.append(f"Alarm started: {opened_at}")
        if duration:
            lines.append(f"Active for: {duration}")
        if metric:
            suffix = f" {unit}" if unit and unit != "/100" else unit
            lines.append(f"{label}: {value}{suffix}")
            if threshold:
                lines.append(f"Threshold: {comparator} {threshold}{suffix}")
        if row.get("step_order"):
            lines.append(f"Escalation level: {row.get('step_order')}")
        lines.extend([
            "",
            "Please check the equipment and acknowledge the alarm in Sentinel.",
            "",
            f"Alarm ID: {row.get('alarm_id')}",
            "Sentinel Cold",
        ])
        return subject, "\n".join(lines)

    @staticmethod
    def _parse_message(message: str) -> tuple[str, str, str, str]:
        match = re.search(r"([a-zA-Z0-9_]+)\s*=\s*([-+0-9.]+)\s*([<>])\s*([-+0-9.]+)", message)
        if not match:
            return "", "", "", ""
        return match.group(1), match.group(2), match.group(3), match.group(4)

    @staticmethod
    def _duration(opened_at: str) -> str:
        if not opened_at:
            return ""
        try:
            opened = datetime.fromisoformat(opened_at.replace("Z", "+00:00")).replace(tzinfo=None)
        except ValueError:
            return ""
        seconds = max(0, int((datetime.now() - opened).total_seconds()))
        if seconds < 60:
            return f"{seconds} s"
        minutes = seconds // 60
        if minutes < 60:
            return f"{minutes} min"
        hours, rem = divmod(minutes, 60)
        return f"{hours} h {rem:02d} min"
