"""Phase 7Q.2 firm branding settings

Revision ID: 20260530_phase_7q2_firm_branding
Revises: 20260529_phase_7h_common_alerts
Create Date: 2026-05-21

Adds tenant-level branding fields and branch-level invoice/payment presentation fields.
The migration is idempotent for SQLite/dev environments.
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260530_phase_7q2_firm_branding"
down_revision = "20260529_phase_7h_common_alerts"
branch_labels = None
depends_on = None


def _columns(table_name: str) -> set[str]:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    if table_name not in inspector.get_table_names():
        return set()
    return {c["name"] for c in inspector.get_columns(table_name)}


def _add_if_missing(table: str, column: sa.Column) -> None:
    if column.name not in _columns(table):
        op.add_column(table, column)


def upgrade() -> None:
    _add_if_missing("tenants", sa.Column("display_name", sa.String(length=200), nullable=True))
    _add_if_missing("tenants", sa.Column("logo_path", sa.String(length=500), nullable=True))
    _add_if_missing("tenants", sa.Column("favicon_path", sa.String(length=500), nullable=True))
    _add_if_missing("tenants", sa.Column("primary_color", sa.String(length=20), nullable=True))
    _add_if_missing("tenants", sa.Column("accent_color", sa.String(length=20), nullable=True))
    _add_if_missing("tenants", sa.Column("website_url", sa.String(length=255), nullable=True))
    _add_if_missing("tenants", sa.Column("contact_email", sa.String(length=255), nullable=True))
    _add_if_missing("tenants", sa.Column("contact_mobile", sa.String(length=50), nullable=True))

    _add_if_missing("branch_settings", sa.Column("invoice_footer_text", sa.Text(), nullable=True))
    _add_if_missing("branch_settings", sa.Column("bank_name", sa.String(length=200), nullable=True))
    _add_if_missing("branch_settings", sa.Column("bank_account_name", sa.String(length=200), nullable=True))
    _add_if_missing("branch_settings", sa.Column("bank_account_number", sa.String(length=50), nullable=True))
    _add_if_missing("branch_settings", sa.Column("bank_ifsc", sa.String(length=20), nullable=True))
    _add_if_missing("branch_settings", sa.Column("upi_id", sa.String(length=100), nullable=True))


def downgrade() -> None:
    # SQLite cannot reliably drop columns on older setups without table rebuild.
    # Keep downgrade no-op to avoid damaging live tenant/branch settings.
    pass
