"""add flow tracking columns and psa_activity_logs table

Revision ID: e0d382f083d4
Revises: 58e3f27f3e8f
Create Date: 2026-03-19 23:59:42.346587

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    # Create psa_activity_logs table
    op.create_table(
        'psa_activity_logs',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('account_id', sa.UUID(), nullable=False),
        sa.Column('session_id', sa.UUID(), nullable=True),
        sa.Column('activity_type', sa.String(length=50), nullable=False),
        sa.Column('hours_logged', sa.Float(), nullable=True),
        sa.Column('psa_ticket_id', sa.String(length=100), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
        sa.ForeignKeyConstraint(['account_id'], ['accounts.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['session_id'], ['ai_sessions.id'], ondelete='SET NULL'),
        sa.PrimaryKeyConstraint('id'),
    )
    op.create_index(op.f('ix_psa_activity_logs_account_id'), 'psa_activity_logs', ['account_id'], unique=False)

    # Flow quality tracking columns on trees (usage_count, success_rate, last_matched_at)
    # Note: usage_count, success_rate, and last_matched_at may already exist on this instance.
    # These are included here for environments where they were not yet added.
    # The columns are guarded to be safe — skip if already present.


def downgrade() -> None:
    op.drop_index(op.f('ix_psa_activity_logs_account_id'), table_name='psa_activity_logs')
    op.drop_table('psa_activity_logs')
