"""Gridoptimization spec hashing

Revision ID: 12d37bad13ba
Revises: 518ee94f4749
Create Date: 2024-12-17 15:41:38.740543

"""

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 = "12d37bad13ba"
down_revision = "518ee94f4749"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "gridoptimization_specification", sa.Column("protocols", postgresql.JSONB(astext_type=sa.Text()), nullable=True)
    )
    op.add_column("gridoptimization_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 gridoptimization_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 gridoptimization_specification SET specification_hash = '{h}' WHERE id = {spec_id};""")
        )

    op.execute(sa.text("UPDATE gridoptimization_specification SET protocols = '{}'::JSONB"))

    op.alter_column("gridoptimization_specification", "specification_hash", nullable=False)
    op.alter_column("gridoptimization_specification", "protocols", nullable=False)

    op.drop_constraint("ux_gridoptimization_specification_keys", "gridoptimization_specification", type_="unique")
    op.drop_column("gridoptimization_specification", "keywords_hash")
    op.create_unique_constraint(
        "ux_gridoptimization_specification_keys",
        "gridoptimization_specification",
        ["specification_hash", "optimization_specification_id"],
    )
    # ### end Alembic commands ###


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