from datetime import datetime

from sqlalchemy import DateTime, Float, Index, String
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class AlertLog(Base):
    """Append-only log of alerts sent (and score watermarks).

    Two uses, distinguished by ``alert_type``:
      - notification dedup: a row records that ``dedup_key`` was alerted at
        ``created_at``; the dispatcher suppresses re-sending the same key within
        a cooldown window.
      - score watermark: rows of type ``score_watermark`` carry the last
        observed composite in ``value``; the latest row per key is the baseline
        for score-deterioration alerts.
    """

    __tablename__ = "alert_log"
    __table_args__ = (
        Index("ix_alert_log_type_key_created", "alert_type", "dedup_key", "created_at"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    alert_type: Mapped[str] = mapped_column(String(30), nullable=False)
    dedup_key: Mapped[str] = mapped_column(String(200), nullable=False)
    value: Mapped[float | None] = mapped_column(Float, nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), default=datetime.utcnow, nullable=False
    )
