"""add sentiment column to comment

Revision ID: 3c0996ae20f3
Revises: e620bf529ed9
Create Date: 2026-02-11 06:43:24.008752

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '3c0996ae20f3'
down_revision = 'e620bf529ed9'
branch_labels = None
depends_on = None

from make_post_sell.models.meta import UUIDType


def _column_exists(table, column):
    conn = op.get_bind()
    result = conn.execute(sa.text(f"PRAGMA table_info({table})"))
    return any(row[1] == column for row in result.fetchall())


def upgrade():
    if not _column_exists("mps_comment", "sentiment"):
        op.add_column(
            "mps_comment",
            sa.Column("sentiment", sa.Integer(), nullable=True),
        )

    # Backfill existing comments
    from make_post_sell.lib.sentiment import classify_sentiment

    conn = op.get_bind()
    rows = conn.execute(
        sa.text("SELECT id, data FROM mps_comment WHERE sentiment IS NULL AND data IS NOT NULL")
    ).fetchall()

    for row in rows:
        comment_id, data = row
        sentiment = classify_sentiment(data)
        conn.execute(
            sa.text("UPDATE mps_comment SET sentiment = :s WHERE id = :id"),
            {"s": sentiment, "id": comment_id},
        )


def downgrade():
    op.drop_column("mps_comment", "sentiment")
