"""Relationship types get isdirectional; flip symmetric legacy types

Adds relationshiptypes.isdirectional (default true). The asset relationships
card uses it: directional types keep a source->target reading, symmetric types
(physical links, network connections) collapse both stored direction rows into
one direction-blind "connected" entry per peer.

Seeds isdirectional=false for the connection-like types present pre-1.0:
Dualpath, connectedto, Cluster Member, Serial Cable, Direct Ethernet, USB,
WiFi. Everything else (controls, Controlled By, Backup For, Master-Slave,
partof, defaultprinter) stays directional.

Idempotent guards so it is safe on a partially-migrated box.

Revision ID: 7d19_relationshiptype_directional
Revises: 7d18_supportteamcontacts
Create Date: 2026-07-11

"""
from alembic import op
import sqlalchemy as sa


revision = '7d19_relationshiptype_directional'
down_revision = '7d18_supportteamcontacts'
branch_labels = None
depends_on = None


# names seeded symmetric (isdirectional=false)
SYMMETRIC_TYPES = [
    'Dualpath',
    'connectedto',
    'Cluster Member',
    'Serial Cable',
    'Direct Ethernet',
    'USB',
    'WiFi',
]


def _has_column(insp, table, column):
    return column in [c['name'] for c in insp.get_columns(table)]


def upgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if not _has_column(insp, 'relationshiptypes', 'isdirectional'):
        op.add_column(
            'relationshiptypes',
            sa.Column('isdirectional', sa.Boolean(), nullable=False,
                      server_default='1'))

    # flip the known symmetric types. re-running just re-sets the same values.
    placeholders = ', '.join([f':n{i}' for i in range(len(SYMMETRIC_TYPES))])
    params = {f'n{i}': name for i, name in enumerate(SYMMETRIC_TYPES)}
    bind.execute(
        sa.text(
            "UPDATE relationshiptypes SET isdirectional = 0 "
            f"WHERE relationshiptype IN ({placeholders})"),
        params)


def downgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)
    if _has_column(insp, 'relationshiptypes', 'isdirectional'):
        op.drop_column('relationshiptypes', 'isdirectional')
