from datetime import datetime
from pydantic import BaseModel, Field


class AlertDefinitionBase(BaseModel):
    name: str = Field(min_length=2, max_length=160)
    description: str | None = None
    target_id: int | None = None
    sql_text: str = Field(min_length=8, max_length=4000)
    comparison: str = "gte"
    warning_threshold: float | None = None
    alert_threshold: float
    enabled: bool = True


class AlertDefinitionCreate(AlertDefinitionBase):
    pass


class AlertDefinitionUpdate(BaseModel):
    name: str | None = Field(default=None, min_length=2, max_length=160)
    description: str | None = None
    target_id: int | None = None
    sql_text: str | None = Field(default=None, min_length=8, max_length=4000)
    comparison: str | None = None
    warning_threshold: float | None = None
    alert_threshold: float | None = None
    enabled: bool | None = None


class AlertDefinitionOut(AlertDefinitionBase):
    id: int
    created_by_user_id: int | None = None
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class AlertDefinitionTestRequest(BaseModel):
    target_id: int
    sql_text: str = Field(min_length=8, max_length=4000)


class AlertDefinitionTestResponse(BaseModel):
    ok: bool
    value: float | None = None
    error: str | None = None


class AlertStatusItem(BaseModel):
    alert_key: str
    source: str
    severity: str
    category: str
    name: str
    description: str
    target_id: int
    target_name: str
    value: float | None = None
    warning_threshold: float | None = None
    alert_threshold: float | None = None
    comparison: str = "gte"
    message: str
    checked_at: datetime
    sql_text: str | None = None


class AlertStatusResponse(BaseModel):
    generated_at: datetime
    warnings: list[AlertStatusItem]
    alerts: list[AlertStatusItem]
    warning_count: int
    alert_count: int


class StandardAlertReferenceItem(BaseModel):
    key: str
    name: str
    checks: str
    comparison: str
    warning: str
    alert: str
