"""reset builtin download profiles: no embedding, 1080p default

Revision ID: 0040_reset_profiles
Revises: 0039_title_normalize
Create Date: 2026-07-03

Redefines the shipped presets: embedding (thumbnail/chapters/subs) is OFF (it rewrites the whole
file — expensive on large videos — and the Plex .nfo/poster sidecars already carry the metadata),
and the default is now 1080p (Best stays available but no longer first). Re-seeds the builtin
rows so both fresh installs (0037 then this) and existing DBs converge on the same set. Existing
jobs are unaffected (they snapshot their spec; profile_id just SET NULLs if it pointed at a
replaced row).
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0040_reset_profiles"
down_revision: Union[str, None] = "0039_title_normalize"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _spec(mode, height=None, container=None, audio_format=None):
    return {
        "mode": mode,
        "max_height": height,
        "container": container,
        "audio_format": audio_format,
        "vcodec": None,
        "embed_subs": False,
        "embed_chapters": False,
        "embed_thumbnail": False,
        "sponsorblock": False,
    }


# Default first (1080p), then Best, then the rest.
_BUILTINS = [
    ("1080p (MP4)", _spec("av", 1080, "mp4"), 10),
    ("Best (MP4)", _spec("av", None, "mp4"), 20),
    ("720p (MP4)", _spec("av", 720, "mp4"), 30),
    ("Audio (M4A)", _spec("a", None, None, "m4a"), 40),
    ("Audio (MP3)", _spec("a", None, None, "mp3"), 50),
    ("Video only (MP4)", _spec("v", None, "mp4"), 60),
]

_profiles = sa.table(
    "download_profiles",
    sa.column("user_id", sa.Integer),
    sa.column("name", sa.String),
    sa.column("spec", sa.JSON),
    sa.column("is_builtin", sa.Boolean),
    sa.column("sort_order", sa.Integer),
)


def upgrade() -> None:
    op.execute("DELETE FROM download_profiles WHERE is_builtin = true")
    op.bulk_insert(
        _profiles,
        [
            {"user_id": None, "name": n, "spec": s, "is_builtin": True, "sort_order": o}
            for n, s, o in _BUILTINS
        ],
    )


def downgrade() -> None:
    # No-op: the previous builtin set was seeded by 0037; not worth reconstructing.
    pass
