import uuid
from datetime import datetime

from sqlalchemy import String, Integer, Float, DateTime, ForeignKey, Index, func
from sqlalchemy import Uuid
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base, JSONType


class MonitoringRecord(Base):
    __tablename__ = "monitoring_records"

    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,
    )
    content_id: Mapped[str | None] = mapped_column(String(36), nullable=True)
    query_keywords: Mapped[str | None] = mapped_column(String(500), nullable=True)
    platform: Mapped[str | None] = mapped_column(String(50), nullable=True)
    baseline_citation_count: Mapped[int] = mapped_column(
        Integer, server_default="0", nullable=False,
    )
    baseline_sentiment: Mapped[float | None] = mapped_column(Float, nullable=True)
    baseline_rank: Mapped[int | None] = mapped_column(Integer, nullable=True)
    current_citation_count: Mapped[int] = mapped_column(
        Integer, server_default="0", nullable=False,
    )
    current_sentiment: Mapped[float | None] = mapped_column(Float, nullable=True)
    current_rank: Mapped[int | None] = mapped_column(Integer, nullable=True)
    change_type: Mapped[str | None] = mapped_column(String(20), nullable=True)
    change_details: Mapped[dict | None] = mapped_column(JSONType, nullable=True)
    check_interval_hours: Mapped[int] = mapped_column(
        Integer, server_default="24", nullable=False,
    )
    last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    next_check_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    status: Mapped[str] = mapped_column(
        String(20), server_default="active", nullable=False,
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        nullable=False,
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    brand: Mapped["Brand"] = relationship("Brand")
    baselines: Mapped[list["ContentBaseline"]] = relationship(
        "ContentBaseline", back_populates="monitoring_record", cascade="all, delete-orphan",
    )

    __table_args__ = (
        Index("idx_monitoring_records_brand_id", "brand_id"),
        Index("idx_monitoring_records_status", "status"),
        Index("idx_monitoring_records_next_check_at", "next_check_at"),
    )


class ContentBaseline(Base):
    __tablename__ = "content_baselines"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        primary_key=True,
        default=uuid.uuid4,
    )
    monitoring_record_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        ForeignKey("monitoring_records.id", ondelete="CASCADE"),
        nullable=False,
    )
    brand_name: Mapped[str] = mapped_column(String(100), nullable=False)
    keyword: Mapped[str] = mapped_column(String(200), nullable=False)
    platform: Mapped[str] = mapped_column(String(50), nullable=False)
    citation_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    sentiment_score: Mapped[float | None] = mapped_column(Float, nullable=True)
    rank_position: Mapped[int | None] = mapped_column(Integer, nullable=True)
    snapshot_data: Mapped[dict | None] = mapped_column(JSONType, nullable=True)
    recorded_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        nullable=False,
    )

    monitoring_record: Mapped["MonitoringRecord"] = relationship(
        "MonitoringRecord", back_populates="baselines",
    )

    __table_args__ = (
        Index("idx_content_baselines_monitoring_record_id", "monitoring_record_id"),
    )
