"""
Alert model — stores alerts generated by the telematics engine.
"""

from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Boolean, Enum as SQLEnum
from sqlalchemy.orm import relationship
from datetime import datetime
import enum

from models.database import Base


class AlertSeverity(str, enum.Enum):
    INFO = "info"
    WARNING = "warning"
    CRITICAL = "critical"


class AlertType(str, enum.Enum):
    SPEEDING = "speeding"
    HARSH_BRAKING = "harsh_braking"
    HARSH_ACCELERATION = "harsh_acceleration"
    ENGINE_OVERHEAT = "engine_overheat"
    LOW_FUEL = "low_fuel"
    LOW_BATTERY = "low_battery"
    DTC_DETECTED = "dtc_detected"
    GEOFENCE_VIOLATION = "geofence_violation"
    EXCESSIVE_IDLE = "excessive_idle"
    MAINTENANCE_DUE = "maintenance_due"
    DEVICE_OFFLINE = "device_offline"


class Alert(Base):
    __tablename__ = "alerts"

    id = Column(Integer, primary_key=True, index=True)
    vehicle_id = Column(Integer, ForeignKey("vehicles.id"), nullable=False, index=True)

    alert_type = Column(SQLEnum(AlertType), nullable=False)
    severity = Column(SQLEnum(AlertSeverity), default=AlertSeverity.WARNING)
    message = Column(String(500), nullable=False)
    details = Column(String(1000), nullable=True)

    # Location when alert triggered
    latitude = Column(Float, nullable=True)
    longitude = Column(Float, nullable=True)

    # Value that triggered the alert
    trigger_value = Column(Float, nullable=True)
    threshold_value = Column(Float, nullable=True)

    # Status
    is_acknowledged = Column(Boolean, default=False)
    acknowledged_by = Column(String(100), nullable=True)
    acknowledged_at = Column(DateTime, nullable=True)

    # Timestamps
    created_at = Column(DateTime, default=datetime.utcnow, index=True)

    # Relationships
    vehicle = relationship("Vehicle", back_populates="alerts")

    def __repr__(self):
        return f"<Alert {self.alert_type.value} vehicle={self.vehicle_id} severity={self.severity.value}>"
