"""add platforms unified array column to comparison_record

展示模型统一数组(pricebot done.params.platforms 原样存): 每平台一行、自带
status/is_best/display, 记录页据此直接渲染, 不再靠 comparison_results + 客户端合并 + 前端派生。
纯新增列, 老记录为空 → 前端回退老 comparison_results。

Revision ID: comparison_platforms_col
Revises: user_manual_risk_fields
"""
from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "comparison_platforms_col"
down_revision: str | None = "user_manual_risk_fields"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

_JSON = sa.JSON().with_variant(postgresql.JSONB(), "postgresql")


def upgrade() -> None:
    # 幂等: 线上为了提前给历史数据补 platforms(2026-07-29), 已手动
    # `ALTER TABLE comparison_record ADD COLUMN IF NOT EXISTS platforms jsonb
    #  NOT NULL DEFAULT '[]'::jsonb`(与本 migration 定义一致)。列已存在时跳过,
    # 否则上线 alembic upgrade head 会撞 DuplicateColumn 直接部署失败。
    bind = op.get_bind()
    cols = {c["name"] for c in sa.inspect(bind).get_columns("comparison_record")}
    if "platforms" in cols:
        return
    with op.batch_alter_table("comparison_record") as batch_op:
        batch_op.add_column(
            sa.Column(
                "platforms", _JSON, nullable=False,
                server_default=sa.text("'[]'"),
            )
        )


def downgrade() -> None:
    with op.batch_alter_table("comparison_record") as batch_op:
        batch_op.drop_column("platforms")
