"""补齐监控审计页面权限。

Revision ID: monitoring_audit_rbac
Revises: merge_signin_boost_main
Create Date: 2026-07-22 00:00:00.000000
"""
from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "monitoring_audit_rbac"
down_revision: str | Sequence[str] | None = "merge_signin_boost_main"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

_JSON = sa.JSON().with_variant(postgresql.JSONB(), "postgresql")
_PAGE = "analytics-health"


def _role_table() -> sa.TableClause:
    return sa.table(
        "admin_role",
        sa.column("name", sa.String),
        sa.column("pages", _JSON),
    )


def upgrade() -> None:
    role = _role_table()
    conn = op.get_bind()
    pages = conn.execute(
        sa.select(role.c.pages).where(role.c.name == "tech")
    ).scalar_one_or_none()
    if pages is not None and _PAGE not in pages:
        conn.execute(
            role.update()
            .where(role.c.name == "tech")
            .values(pages=[*pages, _PAGE])
        )


def downgrade() -> None:
    role = _role_table()
    conn = op.get_bind()
    pages = conn.execute(
        sa.select(role.c.pages).where(role.c.name == "tech")
    ).scalar_one_or_none()
    if pages is not None and _PAGE in pages:
        conn.execute(
            role.update()
            .where(role.c.name == "tech")
            .values(pages=[page for page in pages if page != _PAGE])
        )
