import uuid
from datetime import datetime

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

from app.database import Base


class Suggestion(Base):
    """优化建议模型"""
    __tablename__ = "suggestions"

    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,
    )
    type: Mapped[str] = mapped_column(
        String(50), nullable=False,
        comment="建议类型: content_optimization/platform_targeting/competitor_gap/query_expansion/citation_improvement",
    )
    priority: Mapped[str] = mapped_column(
        String(20), nullable=False, default="medium",
        comment="优先级: high/medium/low",
    )
    title: Mapped[str] = mapped_column(String(200), nullable=False)
    description: Mapped[str] = mapped_column(Text, nullable=False)
    action: Mapped[str | None] = mapped_column(
        Text, nullable=True,
        comment="具体操作步骤",
    )
    expected_impact: Mapped[str | None] = mapped_column(
        String(200), nullable=True,
        comment="预期效果",
    )
    difficulty: Mapped[str] = mapped_column(
        String(20), nullable=False, default="medium",
        comment="难度: easy/medium/hard",
    )
    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default="pending",
        comment="状态: pending/in_progress/completed/dismissed",
    )
    generated_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,
    )
    # 生成批次ID，同一次生成的建议共享同一个batch_id
    batch_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        nullable=False,
        default=uuid.uuid4,
    )
    # 生成来源: rule(规则) / llm(LLM生成)
    source: Mapped[str] = mapped_column(
        String(20), nullable=False, default="rule",
        comment="生成来源: rule/llm",
    )

    brand: Mapped["Brand"] = relationship("Brand", back_populates="suggestions")

    __table_args__ = (
        Index("idx_suggestions_brand_id", "brand_id"),
        Index("idx_suggestions_status", "status"),
        Index("idx_suggestions_type", "type"),
        Index("idx_suggestions_batch_id", "batch_id"),
        Index("idx_suggestions_brand_status", "brand_id", "status"),
    )


# Import at bottom to avoid circular import
from app.models.brand import Brand  # noqa: E402, F401
