from __future__ import annotations

from alembic import context, op
import sqlalchemy as sa

revision = "0008_unique_kb_node"
down_revision = "0007_knowledge_agent_rebuild"
branch_labels = None
depends_on = None


def upgrade() -> None:
    constraints = set() if context.is_offline_mode() else {
        item["name"] for item in sa.inspect(op.get_bind()).get_unique_constraints("sys_knowledge")
    }
    if "uq_knowledge_feishu_node" not in constraints:
        op.create_unique_constraint(
            "uq_knowledge_feishu_node",
            "sys_knowledge",
            ["feishu_space_id", "feishu_node_id"],
        )


def downgrade() -> None:
    constraints = {"uq_knowledge_feishu_node"} if context.is_offline_mode() else {
        item["name"] for item in sa.inspect(op.get_bind()).get_unique_constraints("sys_knowledge")
    }
    if "uq_knowledge_feishu_node" in constraints:
        op.drop_constraint("uq_knowledge_feishu_node", "sys_knowledge", type_="unique")
