"""Remove Flamenco: cancel lingering flamenco jobs, clean up settings.

Revision ID: 032
Revises: 031
Create Date: 2026-03-06
"""
from alembic import op
import sqlalchemy as sa

revision = '032'
down_revision = '031'
branch_labels = None
depends_on = None


def upgrade():
    # Cancel any order lines that were dispatched to Flamenco and never completed
    op.execute("""
        UPDATE order_lines
        SET render_status = 'cancelled',
            render_completed_at = NOW(),
            render_log = render_log || '{"cancelled_reason": "flamenco_removed_in_v2"}'::jsonb
        WHERE render_backend_used = 'flamenco'
          AND render_status IN ('processing', 'pending')
    """)

    # Remove Flamenco-specific system settings
    op.execute("""
        DELETE FROM system_settings
        WHERE key IN ('flamenco_manager_url', 'flamenco_worker_count')
    """)

    # Reset render_backend setting to 'celery' if it was 'flamenco' or 'auto'
    op.execute("""
        UPDATE system_settings
        SET value = 'celery'
        WHERE key = 'render_backend' AND value IN ('flamenco', 'auto')
    """)


def downgrade():
    # Re-insert default Flamenco settings
    op.execute("""
        INSERT INTO system_settings (key, value, updated_at)
        VALUES
            ('flamenco_manager_url', 'http://flamenco-manager:8080', NOW()),
            ('flamenco_worker_count', '1', NOW())
        ON CONFLICT (key) DO NOTHING
    """)
