import uuid
from datetime import datetime

from sqlalchemy import String, ForeignKey, Index, func
from sqlalchemy import Uuid, JSON
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base


class Query(Base):
    __tablename__ = "queries"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        primary_key=True,
        default=uuid.uuid4,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
    )
    keyword: Mapped[str] = mapped_column(String(200), nullable=False)
    target_brand: Mapped[str] = mapped_column(String(100), nullable=False)
    brand_aliases: Mapped[list] = mapped_column(JSON, default=list)
    platforms: Mapped[list] = mapped_column(JSON, nullable=False, default=lambda: ["wenxin", "kimi"])
    frequency: Mapped[str] = mapped_column(String(20), default="weekly")
    status: Mapped[str] = mapped_column(String(20), default="active")
    last_queried_at: Mapped[datetime | None] = mapped_column(nullable=True)
    next_query_at: Mapped[datetime | None] = mapped_column(nullable=True)
    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,
    )

    user: Mapped["User"] = relationship("User", back_populates="queries")
    citation_records: Mapped[list["CitationRecord"]] = relationship(
        "CitationRecord", back_populates="query", cascade="all, delete-orphan"
    )
    query_tasks: Mapped[list["QueryTask"]] = relationship(
        "QueryTask", back_populates="query", cascade="all, delete-orphan"
    )

    __table_args__ = (
        Index("idx_queries_user_id", "user_id"),
        Index("idx_queries_status", "status"),
        Index("idx_queries_next_query_at", "next_query_at"),
    )
