"""Drop the legacy Machine instance layer

Retires the Machine model (ADR-001): the asset/computer model is now the
single source of truth. Drops machines + its PC/status lookups + the legacy
relationship and installed-app tables + the legacy printer extension, and
removes the deprecated communications.machineid column. machinetypes is kept
(still referenced by models.machinetypeid).

Idempotent (IF EXISTS) so it is safe even though the live drop was applied
directly during the cutover.

Revision ID: 7c01_drop_legacy_machine
Revises: 7b02_gaugelabref
Create Date: 2026-06-26

"""
from alembic import op
import sqlalchemy as sa


revision = '7c01_drop_legacy_machine'
down_revision = '7b02_gaugelabref'
branch_labels = None
depends_on = None

_TABLES = ['printerdata', 'installedapps', 'machinerelationships',
           'machines', 'pctypes', 'machinestatuses']


def upgrade():
    bind = op.get_bind()
    bind.exec_driver_sql("SET FOREIGN_KEY_CHECKS=0")
    insp = sa.inspect(bind)
    if 'machineid' in [c['name'] for c in insp.get_columns('communications')]:
        for fk in insp.get_foreign_keys('communications'):
            if 'machineid' in fk['constrained_columns'] and fk.get('name'):
                bind.exec_driver_sql(
                    f"ALTER TABLE communications DROP FOREIGN KEY {fk['name']}")
        op.drop_column('communications', 'machineid')
    for t in _TABLES:
        bind.exec_driver_sql(f"DROP TABLE IF EXISTS {t}")
    bind.exec_driver_sql("SET FOREIGN_KEY_CHECKS=1")


def downgrade():
    # The Machine layer is retired; recreating it is out of scope.
    raise NotImplementedError("Legacy Machine layer cannot be restored")
