"""comparison_record.fail_reason (失败卡展示原因)

Revision ID: comparison_record_fail_reason
Revises: user_manual_risk_fields
Create Date: 2026-07-28 12:00:00.000000

失败记录的展示原因:information 具体则=它;笼统则由写路径从 platform_results 捞出的
业务原因;纯系统失败为 None(端侧品牌兜底)。见 repositories.comparison._derive_fail_display。
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'comparison_record_fail_reason'
down_revision: Union[str, Sequence[str], None] = 'user_manual_risk_fields'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    with op.batch_alter_table('comparison_record', schema=None) as batch_op:
        batch_op.add_column(sa.Column('fail_reason', sa.String(length=256), nullable=True))
    # 回填老失败记录:information 具体的直接搬过来(笼统/系统失败留 None → 端侧品牌兜底)。
    # 新记录由写路径 _derive_fail_display 落库(含 platform_results 救援/补判),不走这条。
    # platform_results 只在 raw_payload 里,SQL 里不易解析,故老记录不做救援/补判(可接受:
    # 老 mixed/打烊记录回退品牌兜底);具体 information 的老记录本次即可显示真实原因。
    op.execute(
        """
        UPDATE comparison_record
        SET fail_reason = information
        WHERE status = 'failed'
          AND information IS NOT NULL
          AND information <> ''
          AND information NOT IN (
              '比价过程出错，请稍后重试',
              '比价出错',
              '比价未完成',
              'done 参数缺少可验证的目标平台结果'
          )
        """
    )


def downgrade() -> None:
    with op.batch_alter_table('comparison_record', schema=None) as batch_op:
        batch_op.drop_column('fail_reason')
