"""Add columns to analytics to record provided namespace name, module name and provider

Revision ID: 7b6cac0d522f
Revises: 81609b772646
Create Date: 2023-08-19 14:28:38.619995

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '7b6cac0d522f'
down_revision = '81609b772646'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('analytics', sa.Column('namespace_name', sa.String(length=128), nullable=True))
    op.add_column('analytics', sa.Column('module_name', sa.String(length=128), nullable=True))
    op.add_column('analytics', sa.Column('provider_name', sa.String(length=128), nullable=True))

    # Populate new columns for analytics
    # NOTE: This is not the most efficient way (AT ALL!),
    # but certainly compatible between SQLite and MySQL
    bind = op.get_bind()

    module_version_rows = bind.execute("""
        SELECT mv.id, ns.namespace, mp.module, mp.provider
        FROM module_version mv
        INNER JOIN module_provider mp
            ON mv.module_provider_id=mp.id
        INNER JOIN namespace ns
            ON mp.namespace_id=ns.id
    """)
    module_version_lookup = {
        row[0]: row[1:]
        for row in module_version_rows
    }

    analytics_rows = bind.execute("SELECT id, parent_module_version FROM analytics")
    for row in analytics_rows:
        analytics_id, module_version_id = row

        if module_version_id in module_version_lookup:
            namespace_name, module_name, provider_name = module_version_lookup[module_version_id]
            bind.execute(
                sa.sql.text(
                    """
                    UPDATE analytics
                    SET namespace_name=:namespace_name,
                        module_name=:module_name,
                        provider_name=:provider_name
                    WHERE id=:analytics_id"""
                ),
                analytics_id=analytics_id,
                namespace_name=namespace_name,
                provider_name=provider_name,
                module_name=module_name
            )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('analytics') as analytics_batch:
        analytics_batch.drop_column('provider_name')
        analytics_batch.drop_column('module_name')
        analytics_batch.drop_column('namespace_name')
    # ### end Alembic commands ###
