import uuid
from datetime import datetime

from sqlalchemy import String, Integer, Float, ForeignKey, Index, func, Text
from sqlalchemy import Uuid, JSON
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class TrendInsight(Base):
    __tablename__ = "trend_insights"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        primary_key=True,
        default=uuid.uuid4,
    )
    brand_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        ForeignKey("brands.id", ondelete="CASCADE"),
        nullable=False,
    )
    trend_type: Mapped[str] = mapped_column(String(20), nullable=False)
    keyword: Mapped[str | None] = mapped_column(String(200), nullable=True)
    platform: Mapped[str | None] = mapped_column(String(50), nullable=True)
    period_start: Mapped[datetime] = mapped_column(nullable=False)
    period_end: Mapped[datetime] = mapped_column(nullable=False)
    data_points: Mapped[list | None] = mapped_column(JSON, nullable=True)
    change_rate: Mapped[float | None] = mapped_column(Float, nullable=True)
    absolute_change: Mapped[int | None] = mapped_column(Integer, nullable=True)
    sentiment_trend: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    cause_analysis: Mapped[str | None] = mapped_column(Text, nullable=True)
    recommendations: Mapped[list | None] = mapped_column(JSON, nullable=True)
    confidence: Mapped[float] = mapped_column(Float, nullable=False, default=0.5)
    severity: Mapped[str] = mapped_column(
        String(20), nullable=False, server_default="info",
    )
    created_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        nullable=False,
    )
    updated_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    __table_args__ = (
        Index("idx_trend_insights_brand_id", "brand_id"),
        Index("idx_trend_insights_trend_type", "trend_type"),
        Index("idx_trend_insights_created_at", "created_at"),
        Index("idx_trend_insights_period_start", "period_start"),
    )
