"""add account_id to core session tables

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

revision: str = 'cc214c63aa30'
down_revision: Union[str, None] = '064'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = ('067',)


def upgrade() -> None:
    # ── Step 1: ADD COLUMN (nullable) ────────────────────────────────────────
    for table in ('sessions', 'attachments', 'session_supporting_data',
                  'session_resolution_outputs'):
        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',
        )

    # ── Step 2: BACKFILL ─────────────────────────────────────────────────────
    # sessions: direct join to users
    op.execute("""
        UPDATE sessions s
        SET account_id = u.account_id
        FROM users u
        WHERE s.user_id = u.id
          AND s.account_id IS NULL
    """)

    # attachments: chain through sessions (now backfilled above)
    op.execute("""
        UPDATE attachments a
        SET account_id = s.account_id
        FROM sessions s
        WHERE a.session_id = s.id
          AND a.account_id IS NULL
    """)

    # session_supporting_data: same chain
    op.execute("""
        UPDATE session_supporting_data sd
        SET account_id = s.account_id
        FROM sessions s
        WHERE sd.session_id = s.id
          AND sd.account_id IS NULL
    """)

    # session_resolution_outputs: FK is to ai_sessions, not sessions
    op.execute("""
        UPDATE session_resolution_outputs sro
        SET account_id = ai.account_id
        FROM ai_sessions ai
        WHERE sro.session_id = ai.id
          AND sro.account_id IS NULL
    """)

    # ── Step 3: VERIFY zero NULLs — raises if any remain ────────────────────
    for table in ('sessions', 'attachments', 'session_supporting_data',
                  'session_resolution_outputs'):
        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 remain in {table}. "
                f"Fix the backfill before re-running."
            )

    # ── Step 4: SET NOT NULL ─────────────────────────────────────────────────
    for table in ('sessions', 'attachments', 'session_supporting_data',
                  'session_resolution_outputs'):
        op.alter_column(table, 'account_id', nullable=False)

    # ── Step 5: CREATE INDEX ─────────────────────────────────────────────────
    for table in ('sessions', 'attachments', 'session_supporting_data',
                  'session_resolution_outputs'):
        op.create_index(f'ix_{table}_account_id', table, ['account_id'])


def downgrade() -> None:
    for table in ('sessions', 'attachments', 'session_supporting_data',
                  'session_resolution_outputs'):
        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')
