"""Optimization spec hashing

Revision ID: e04bf1eedfbc
Revises: 6b758fd53ff0
Create Date: 2024-12-17 10:50:37.251828

"""

import sqlalchemy as sa
from alembic import op

from migration_helpers.hashing import hash_dict_1

# revision identifiers, used by Alembic.
revision = "e04bf1eedfbc"
down_revision = "6b758fd53ff0"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("optimization_specification", sa.Column("specification_hash", sa.String(), nullable=True))

    # Generate hashes for existing specs
    conn = op.get_bind()
    res = conn.execute(sa.text(f"SELECT id, program, keywords, protocols FROM optimization_specification;"))
    all_spec = res.fetchall()
    for spec_id, program, keywords, protocols in all_spec:
        d = {
            "program": program,
            "keywords": keywords,
            "protocols": protocols,
        }
        h = hash_dict_1(d)
        op.execute(
            sa.text(f"""UPDATE optimization_specification SET specification_hash = '{h}' WHERE id = {spec_id};""")
        )

    op.alter_column("optimization_specification", "specification_hash", nullable=False)
    op.drop_constraint("ux_optimization_specification_keys", "optimization_specification", type_="unique")
    op.drop_column("optimization_specification", "keywords_hash")
    op.create_unique_constraint(
        "ux_optimization_specification_keys",
        "optimization_specification",
        ["specification_hash", "qc_specification_id"],
    )
    # ### end Alembic commands ###


def downgrade():
    raise RuntimeError("Downgrade not supported.")
