"""fc2d-vii-c: image_record.artist_id + backfill + drop artist tags

Revision ID: 0008
Revises: 0007
Create Date: 2026-05-18

Internal forward-correctness migration (the big legacy-import migration
stays deferred). downgrade() does NOT recreate deleted artist tags;
downgrade is dev-only and the data is reconstructable by re-import.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

from backend.app.utils.artist_backfill import (
    BACKFILL_PRIMARY_SQL,
    BACKFILL_PROVENANCE_SQL,
    BACKFILL_TAG_SQL,
    DELETE_ARTIST_TAGS_SQL,
)

revision: str = "0008"
down_revision: Union[str, None] = "0007"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.add_column(
        "image_record",
        sa.Column("artist_id", sa.Integer(), nullable=True),
    )
    op.create_foreign_key(
        "fk_image_record_artist_id", "image_record", "artist",
        ["artist_id"], ["id"], ondelete="SET NULL",
    )
    op.create_index(
        "ix_image_record_artist_id", "image_record", ["artist_id"],
    )
    op.execute(BACKFILL_PRIMARY_SQL)
    op.execute(BACKFILL_PROVENANCE_SQL)
    op.execute(BACKFILL_TAG_SQL)
    op.execute(DELETE_ARTIST_TAGS_SQL)


def downgrade() -> None:
    op.drop_index("ix_image_record_artist_id", table_name="image_record")
    op.drop_constraint(
        "fk_image_record_artist_id", "image_record", type_="foreignkey"
    )
    op.drop_column("image_record", "artist_id")
