"""add account_id to step_ratings and step_usage_log

Revision ID: 7167e9374b0c
Revises: 478c159e5654
Create Date: 2026-04-09 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa

revision: str = '7167e9374b0c'
down_revision: Union[str, None] = '478c159e5654'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    for table in ('step_ratings', 'step_usage_log'):
        op.add_column(table, sa.Column('account_id', sa.UUID(), nullable=True))
        op.create_foreign_key(
            f'fk_{table}_account_id', table, 'accounts',
            ['account_id'], ['id'], ondelete='CASCADE',
        )
        # Backfill: from the RATER/LOGGER user's account (not the step's account)
        op.execute(f"""
            UPDATE {table} t
            SET account_id = u.account_id
            FROM users u
            WHERE t.user_id = u.id
              AND t.account_id IS NULL
        """)
        result = op.get_bind().execute(
            sa.text(f"SELECT COUNT(*) FROM {table} WHERE account_id IS NULL")
        )
        count = result.scalar()
        if count > 0:
            raise RuntimeError(f"ROLLBACK: {count} NULL account_id rows in {table}.")
        op.alter_column(table, 'account_id', nullable=False)
        op.create_index(f'ix_{table}_account_id', table, ['account_id'])


def downgrade() -> None:
    for table in ('step_ratings', 'step_usage_log'):
        op.drop_index(f'ix_{table}_account_id', table_name=table)
        op.drop_constraint(f'fk_{table}_account_id', table, type_='foreignkey')
        op.drop_column(table, 'account_id')
