"""add public.organizations.locale and public.users.locale

Interface language, stored as a preference and applied at render time only —
the same shape as the timezone columns (tz001 / ar003). NULL on a user means
"inherit the org locale", which itself defaults to English, so no backfill is
needed and every existing account keeps the interface it has today.

Revision ID: i18n001
Revises: sep001
Create Date: 2026-09-03
"""
from alembic import op
import sqlalchemy as sa

revision = 'i18n001'
down_revision = 'sep001'
branch_labels = None
depends_on = None


def _public_column_exists(conn, table, column):
    return conn.execute(sa.text(
        "SELECT 1 FROM information_schema.columns "
        "WHERE table_schema='public' AND table_name=:t AND column_name=:c"
    ), {"t": table, "c": column}).fetchone() is not None


def upgrade():
    conn = op.get_bind()
    if not _public_column_exists(conn, 'organizations', 'locale'):
        op.add_column(
            'organizations',
            sa.Column('locale', sa.String(5), nullable=False, server_default='en'),
            schema='public',
        )
    if not _public_column_exists(conn, 'users', 'locale'):
        op.add_column('users', sa.Column('locale', sa.String(5), nullable=True),
                      schema='public')


def downgrade():
    op.drop_column('users', 'locale', schema='public')
    op.drop_column('organizations', 'locale', schema='public')
