"""Add Flamenco render backend support

Revision ID: 015
Revises: 014
Create Date: 2026-03-02

"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa

revision: str = "015"
down_revision: Union[str, None] = "014"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # output_types: render_backend + is_animation
    op.add_column(
        "output_types",
        sa.Column("render_backend", sa.String(20), server_default="auto", nullable=False),
    )
    op.add_column(
        "output_types",
        sa.Column("is_animation", sa.Boolean(), server_default="false", nullable=False),
    )

    # order_lines: flamenco tracking columns
    op.add_column(
        "order_lines",
        sa.Column("flamenco_job_id", sa.String(100), nullable=True),
    )
    op.add_column(
        "order_lines",
        sa.Column("render_backend_used", sa.String(20), nullable=True),
    )
    op.add_column(
        "order_lines",
        sa.Column("render_started_at", sa.DateTime(), nullable=True),
    )
    op.add_column(
        "order_lines",
        sa.Column("render_completed_at", sa.DateTime(), nullable=True),
    )

    # Seed system settings for Flamenco
    op.execute(
        "INSERT INTO system_settings (key, value) VALUES "
        "('render_backend', 'celery'), "
        "('flamenco_manager_url', 'http://flamenco-manager:8080'), "
        "('flamenco_worker_count', '1') "
        "ON CONFLICT (key) DO NOTHING"
    )


def downgrade() -> None:
    op.drop_column("order_lines", "render_completed_at")
    op.drop_column("order_lines", "render_started_at")
    op.drop_column("order_lines", "render_backend_used")
    op.drop_column("order_lines", "flamenco_job_id")
    op.drop_column("output_types", "is_animation")
    op.drop_column("output_types", "render_backend")

    op.execute("DELETE FROM system_settings WHERE key IN ('render_backend', 'flamenco_manager_url', 'flamenco_worker_count')")
