"""Alert rules and events for Mission Control monitoring."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID, uuid4

from sqlalchemy import JSON, Column, Index
from sqlmodel import Field

from app.core.time import utcnow
from app.models.base import QueryModel


class AlertRule(QueryModel, table=True):
    """Configurable alert rules for monitoring thresholds."""

    __tablename__ = "alert_rules"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    gateway_id: UUID | None = Field(default=None, foreign_key="gateways.id", index=True)
    name: str = Field(nullable=False)
    metric_type: str = Field(nullable=False, index=True)
    threshold: float = Field(nullable=False)
    comparison: str = Field(default="gt", nullable=False)
    enabled: bool = Field(default=True)
    cooldown_minutes: int = Field(default=60)
    description: str | None = Field(default=None)
    metadata_: dict | None = Field(default=None, sa_column=Column(JSON))
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_alert_rules_org_created", "organization_id", "created_at"),
        Index("ix_alert_rules_org_gateway", "organization_id", "gateway_id"),
    )


class AlertEvent(QueryModel, table=True):
    """Triggered alert instances — one row per alert fired."""

    __tablename__ = "alert_events"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(default=None, foreign_key="organizations.id", index=True)
    rule_id: UUID = Field(default=None, foreign_key="alert_rules.id", index=True)
    gateway_id: UUID | None = Field(default=None, foreign_key="gateways.id", index=True)
    metric_type: str = Field(nullable=False, index=True)
    triggered_value: float = Field(nullable=False)
    threshold_value: float = Field(nullable=False)
    acknowledged: bool = Field(default=False)
    acknowledged_at: datetime | None = Field(default=None)
    acknowledged_by: UUID | None = Field(default=None, foreign_key="users.id", nullable=True)
    resolved_at: datetime | None = Field(default=None)
    metadata_: dict | None = Field(default=None, sa_column=Column(JSON))
    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index("ix_alert_events_org_created", "organization_id", "created_at"),
        Index("ix_alert_events_org_gateway", "organization_id", "gateway_id"),
        Index("ix_alert_events_rule_created", "rule_id", "created_at"),
    )
