"""Add file-field provenance to the file_attachment entity.

Revision ID: 173
Revises: 172
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "173"
down_revision = "172"
branch_labels = None
depends_on = None


def upgrade() -> None:
    feature_packs = sa.table(
        "feature_packs",
        sa.column("slug", sa.String),
        sa.column("composition", postgresql.JSONB),
    )
    connection = op.get_bind()
    row = connection.execute(
        sa.text("SELECT composition FROM feature_packs WHERE slug = 'file-attachments'")
    ).first()
    if not row or not row[0]:
        return
    composition = row[0]
    for entity in composition.get("entities", []):
        if entity.get("entity_key") != "file_attachment":
            continue
        fields = entity.setdefault("schema", {}).setdefault("fields", [])
        additions = [
            ("field_key", "Source Field", "text", True),
            ("source_event_id", "Source Event", "text", True),
            ("uploaded_by_user_id", "Uploaded By", "text", False),
            ("is_current", "Current", "boolean", False),
            ("superseded_at", "Superseded At", "text", False),
            ("superseded_by_attachment_id", "Superseded By", "text", False),
        ]
        for key, name, field_type, indexed in additions:
            if not any(field.get("key") == key for field in fields):
                fields.append({
                    "key": key,
                    "name": name,
                    "type": field_type,
                    "required": False,
                    "indexed": indexed,
                })
    connection.execute(
        feature_packs.update()
        .where(feature_packs.c.slug == "file-attachments")
        .values(composition=composition)
    )


def downgrade() -> None:
    # Keep existing provenance data intact on downgrade.
    pass
