"""park_screens 绑定字段（status/code/code_expires/bound_at），tenant_id 可空（幂等）

Revision ID: 0002_park_screen_bind
Revises: 0001_initial
Create Date: 2026-08-24
"""
from __future__ import annotations

import sqlalchemy as sa
from alembic import op

revision = "0002_park_screen_bind"
down_revision = "0001_initial"
branch_labels = None
depends_on = None


def _existing_cols(table: str) -> set[str]:
    conn = op.get_bind()
    rows = conn.exec_driver_sql(f"PRAGMA table_info({table})").fetchall()
    return {r[1] for r in rows}


def upgrade() -> None:
    cols = _existing_cols("park_screens")
    spec = {
        "status": sa.Column("status", sa.String(), server_default="unbound"),
        "code": sa.Column("code", sa.String(), server_default=""),
        "code_expires": sa.Column("code_expires", sa.String(), server_default=""),
        "bound_at": sa.Column("bound_at", sa.String(), server_default=""),
    }
    for name, col in spec.items():
        if name not in cols:
            op.add_column("park_screens", col)


def downgrade() -> None:
    cols = _existing_cols("park_screens")
    for name in ("status", "code", "code_expires", "bound_at"):
        if name in cols:
            op.drop_column("park_screens", name)
