from __future__ import annotations

from datetime import datetime
from decimal import Decimal

from sqlalchemy import BigInteger, Index, Integer, Numeric, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column

from supply_infra.db.base import Base


class GeneratedDemand(Base):
    """单维度需求产生结果。"""

    __tablename__ = "generated_demand"
    __table_args__ = (
        Index("idx_generated_demand_dim_biz", "source_dim", "biz_dt"),
        Index("idx_generated_demand_name", "demand_name"),
        Index("idx_generated_demand_run", "run_id"),
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    source_dim: Mapped[str] = mapped_column(String(32), nullable=False, comment="来源热度维度")
    overall_direction: Mapped[str] = mapped_column(
        String(256), nullable=False, comment="整体方向"
    )
    summary_event: Mapped[str] = mapped_column(String(512), nullable=False, comment="汇总事件")
    demand_name: Mapped[str] = mapped_column(
        String(256), nullable=False, comment="需求名称（来自 demand_belong_category.name）"
    )
    demand_belong_id: Mapped[int | None] = mapped_column(
        BigInteger, nullable=True, comment="demand_belong_category.id"
    )
    category_id: Mapped[int | None] = mapped_column(
        BigInteger, nullable=True, comment="选用时的类目 id"
    )
    category_path: Mapped[str | None] = mapped_column(
        String(1024), nullable=True, comment="类目路径文本"
    )
    dim_avg: Mapped[Decimal | None] = mapped_column(
        Numeric(16, 8), nullable=True, comment="落库时该维 avg 快照"
    )
    dim_count: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="落库时该维 count 快照"
    )
    reason: Mapped[str | None] = mapped_column(Text, nullable=True, comment="选用理由")
    biz_dt: Mapped[str | None] = mapped_column(
        String(32), nullable=True, comment="对齐热度统计日 YYYYMMDD"
    )
    run_id: Mapped[str] = mapped_column(String(64), nullable=False, comment="同一次生成批次")
    is_delete: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="是否删除 0-正常 1-删除"
    )
    create_time: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        comment="创建时间",
    )
    update_time: Mapped[datetime] = mapped_column(
        nullable=False,
        server_default=func.now(),
        onupdate=func.now(),
        comment="更新时间",
    )
