"""Reaction spec hashing

Revision ID: a3c51b03bc19
Revises: 12d37bad13ba
Create Date: 2024-12-17 17:12:43.414568

"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

from qcfractal.alembic.migration_helpers.hashing import hash_dict_1

# revision identifiers, used by Alembic.
revision = "a3c51b03bc19"
down_revision = "12d37bad13ba"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "reaction_specification", sa.Column("protocols", postgresql.JSONB(astext_type=sa.Text()), nullable=True)
    )
    op.add_column("reaction_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 FROM reaction_specification;"))
    all_spec = res.fetchall()
    for spec_id, program, keywords in all_spec:
        d = {
            "program": program,
            "keywords": keywords,
            "protocols": {},  # Default for now
        }
        h = hash_dict_1(d)
        op.execute(sa.text(f"""UPDATE reaction_specification SET specification_hash = '{h}' WHERE id = {spec_id};"""))
    op.execute(sa.text("UPDATE reaction_specification SET protocols = '{}'::JSONB"))

    op.alter_column("reaction_specification", "protocols", nullable=False)
    op.alter_column("reaction_specification", "specification_hash", nullable=False)
    op.drop_constraint("ux_reaction_specification_keys", "reaction_specification", type_="unique")
    op.drop_column("reaction_specification", "keywords_hash")
    op.create_unique_constraint(
        "ux_reaction_specification_keys",
        "reaction_specification",
        ["specification_hash", "singlepoint_specification_id", "optimization_specification_id"],
    )
    # ### end Alembic commands ###


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