"""004_flywheel_preference_events

Revision ID: 004
Revises: 003
Create Date: 2026-06-09
Alembic 004: 飞轮信号表
preference_events 一期建表写入
preference_profile 二期预留，一期不建
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "004"
down_revision: Union[str, None] = "003"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

_SIGNAL_TYPE = sa.Enum(
    "text_select", "image_select", "approve",
    "reject_with_reason", "regenerate",
    name="signaltype",
)
_DATA_OWNERSHIP = sa.Enum("client_data", "platform_asset", name="dataownership")


def upgrade() -> None:
    op.create_table(
        "preference_events",
        sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column("workspace_id", sa.BigInteger(), nullable=False),
        sa.Column("product_id", sa.BigInteger(), nullable=False),
        sa.Column("task_id", sa.BigInteger(), nullable=False),
        sa.Column("user_id", sa.BigInteger(), nullable=False),
        sa.Column("signal_type", _SIGNAL_TYPE, nullable=False),
        sa.Column("signal_weight", sa.Integer(), nullable=False),
        sa.Column("candidate_id", sa.BigInteger(), nullable=True),
        sa.Column("angle_label", sa.String(64), nullable=True),
        sa.Column("reason", sa.Text(), nullable=True),
        sa.Column("signal_meta", sa.Text(), nullable=True),
        sa.Column(
            "data_ownership", _DATA_OWNERSHIP,
            nullable=False, server_default="client_data",
        ),
        sa.Column(
            "created_at", sa.DateTime(),
            server_default=sa.text("now()"), nullable=False,
        ),
        sa.ForeignKeyConstraint(["product_id"], ["products.id"]),
        sa.ForeignKeyConstraint(["task_id"], ["generation_tasks.id"]),
        sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(
        "idx_preference_events_ws_product_created",
        "preference_events",
        ["workspace_id", "product_id", "created_at"],
    )
    # preference_profile 二期预留，一期不建


def downgrade() -> None:
    op.drop_index("idx_preference_events_ws_product_created", "preference_events")
    op.drop_table("preference_events")
    # MySQL 不支持 DROP TYPE，枚举存 VARCHAR 无需清理
