"""keep only the latest knowledge version

Revision ID: 0012_knowledge_latest_only
Revises: 0011_knowledge_auto_publish
"""

from alembic import op


revision = "0012_knowledge_latest_only"
down_revision = "0011_knowledge_auto_publish"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute("UPDATE sys_knowledge SET pending_version_id = NULL")
    for table in (
        "sys_knowledge_review_record",
        "sys_knowledge_card",
        "sys_knowledge_chunk",
        "sys_knowledge_section",
        "sys_knowledge_manifest",
    ):
        op.execute(
            f"""
            DELETE detail
            FROM {table} AS detail
            JOIN sys_knowledge AS knowledge ON knowledge.id = detail.knowledge_id
            WHERE knowledge.current_version_id IS NULL
               OR detail.version_id <> knowledge.current_version_id
            """
        )
    op.execute(
        """
        DELETE version
        FROM sys_knowledge_version AS version
        JOIN sys_knowledge AS knowledge ON knowledge.id = version.knowledge_id
        WHERE knowledge.current_version_id IS NULL
           OR version.id <> knowledge.current_version_id
        """
    )
    op.execute(
        """
        DELETE snapshot
        FROM sys_knowledge_source_snapshot AS snapshot
        LEFT JOIN sys_knowledge_version AS version ON version.snapshot_id = snapshot.id
        WHERE version.id IS NULL
        """
    )


def downgrade() -> None:
    # Removed historical content cannot be reconstructed from the latest version.
    pass
