"""llm_call_log.metadata_json TEXT column 추가 (Phase 4 iter 7 W3+I1).

scene_image_gen / ref_image_gen 호출에 PID/EID 외에 scene_index / shot_index
/ still_id / entity_id 같은 free-form 추적 정보를 보존하기 위한 JSON column.
schema-level structured query 보다 incident triage 시 grep 가능한 추적 신호
가 우선이라 단일 TEXT (JSON serialized dict) 로 통일.

기존 column (project_id, episode_id, operation_type, step_name) 으로는 fan-out
이 큰 image step 의 단위 추적 (어느 still 이 어느 LLM 호출과 매핑되는지) 가
막혀 있었음 — 1020 image-related row 모두 PID/EID 도 NULL 인 사고 가
운영 중 발견됨 (Phase 4 iter 7 W3 회복 작업의 일부).

Revision ID: 006_llm_call_log_metadata_json
Revises: 005_file_path_relative_check
Create Date: 2026-05-07
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "006_llm_call_log_metadata_json"
down_revision: Union[str, None] = "005_file_path_relative_check"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Phase 4 iter 7 review B1 — inspector 기반 idempotent. startup `_migrations`
    # 의 IF NOT EXISTS path 가 이미 column 을 추가했을 수 있어 alembic 만 stamp
    # 안 된 상태에서 upgrade 시 duplicate-column 사고가 재발하는 것을 차단.
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    existing = {col["name"] for col in inspector.get_columns("llm_call_log")}
    if "metadata_json" not in existing:
        op.add_column(
            "llm_call_log",
            sa.Column("metadata_json", sa.Text(), nullable=True),
        )


def downgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    existing = {col["name"] for col in inspector.get_columns("llm_call_log")}
    if "metadata_json" in existing:
        op.drop_column("llm_call_log", "metadata_json")
