"""Add origin_app column to ap_activities

Revision ID: o5m3j9k1l2
Revises: n4l2i8j0k1
Create Date: 2026-02-22
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect as sa_inspect

revision = "o5m3j9k1l2"
down_revision = "n4l2i8j0k1"
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()
    inspector = sa_inspect(conn)
    columns = [c["name"] for c in inspector.get_columns("ap_activities")]
    if "origin_app" not in columns:
        op.add_column(
            "ap_activities",
            sa.Column("origin_app", sa.String(64), nullable=True),
        )
    # Index is idempotent with if_not_exists
    op.create_index(
        "ix_ap_activity_origin_app", "ap_activities", ["origin_app"],
        if_not_exists=True,
    )


def downgrade() -> None:
    op.drop_index("ix_ap_activity_origin_app", table_name="ap_activities")
    op.drop_column("ap_activities", "origin_app")
