"""comparison_record: 客户端环境 / 性能统计 / LLM 明细 debug 字段

Revision ID: comparison_debug_fields
Revises: cps_activity_image
Create Date: 2026-06-17 22:00:00.000000

给 admin 比价记录 debug 页新增采集列，全部 nullable(旧记录 / 未发版客户端为 NULL，向后兼容)：
- 客户端环境: device_*/rom_*/android_*/app_version*/source_app_version/经纬度
- 过程统计: total_ms/step_count/llm_call_count/retry_count
- LLM 明细: llm_calls(JSONB，server 按 trace_id 同机拉 pricebot 落库)
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


revision: str = "comparison_debug_fields"
down_revision: Union[str, Sequence[str], None] = "cps_activity_image"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

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


def upgrade() -> None:
    op.add_column("comparison_record", sa.Column("device_model", sa.String(64), nullable=True))
    op.add_column("comparison_record", sa.Column("device_manufacturer", sa.String(64), nullable=True))
    op.add_column("comparison_record", sa.Column("rom_vendor", sa.String(32), nullable=True))
    op.add_column("comparison_record", sa.Column("rom_name", sa.String(32), nullable=True))
    op.add_column("comparison_record", sa.Column("rom_version", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("android_version", sa.String(16), nullable=True))
    op.add_column("comparison_record", sa.Column("android_sdk", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("app_version", sa.String(32), nullable=True))
    op.add_column("comparison_record", sa.Column("app_version_code", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("source_app_version", sa.String(32), nullable=True))
    op.add_column("comparison_record", sa.Column("longitude", sa.Float(), nullable=True))
    op.add_column("comparison_record", sa.Column("latitude", sa.Float(), nullable=True))
    op.add_column("comparison_record", sa.Column("total_ms", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("step_count", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("llm_call_count", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("retry_count", sa.Integer(), nullable=True))
    op.add_column("comparison_record", sa.Column("llm_calls", _JSONB, nullable=True))


def downgrade() -> None:
    for col in (
        "llm_calls", "retry_count", "llm_call_count", "step_count", "total_ms",
        "latitude", "longitude", "source_app_version", "app_version_code",
        "app_version", "android_sdk", "android_version", "rom_version",
        "rom_name", "rom_vendor", "device_manufacturer", "device_model",
    ):
        op.drop_column("comparison_record", col)
