"""Record the professional software job that produced an artifact.

Revision ID: 0033
Revises: 0032
Create Date: 2026-08-14
"""
from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision: str = "0033"
down_revision: str | None = "0032"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.add_column(
        "artifacts",
        sa.Column("software_job_id", postgresql.UUID(as_uuid=True), nullable=True),
    )
    op.create_index(
        "ix_artifacts_software_job_id", "artifacts", ["software_job_id"]
    )
    # 0032 已发布任务的 manifest 保存了平台 artifact UUID，可无损补来源。
    op.execute(
        sa.text(
            """
            UPDATE artifacts AS artifact
            SET software_job_id = job.job_id
            FROM software_jobs AS job,
                 LATERAL jsonb_array_elements(job.artifact_manifest) AS output
            WHERE output->>'artifact_id' = artifact.artifact_id::text
              AND output->>'source_artifact_id' NOT IN ('plot_spec', 'provenance')
              AND artifact.software_job_id IS NULL
            """
        )
    )


def downgrade() -> None:
    op.drop_index("ix_artifacts_software_job_id", table_name="artifacts")
    op.drop_column("artifacts", "software_job_id")
