"""Add local_flights table for tracking local flights

Revision ID: 002_local_flights
Revises: 001_initial_schema
Create Date: 2025-12-12 12:00:00.000000

This migration adds a new table for tracking local flights (circuits, local, departure)
that don't require PPR submissions. Also adds etd and renames booked_out_dt to created_dt,
and departure_dt to departed_dt for consistency. Transforms journal table from PPR-specific
to a generic polymorphic journal for all entity types.

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '002_local_flights'
down_revision = '001_initial_schema'
branch_labels = None
depends_on = None


def upgrade() -> None:
    """
    Create local_flights, departures, and arrivals tables.
    Transform journal table from PPR-specific to generic polymorphic journal.
    """
    
    # Modify existing journal table to support all entity types
    # First add new columns (check if they don't already exist)
    from sqlalchemy import inspect, text
    from alembic import op
    
    # Get table columns to check if entity_type and entity_id already exist
    connection = op.get_context().bind
    inspector = inspect(connection)
    columns = [col['name'] for col in inspector.get_columns('journal')]
    
    if 'entity_type' not in columns:
        op.add_column('journal', sa.Column('entity_type', sa.String(50), nullable=True))
    if 'entity_id' not in columns:
        op.add_column('journal', sa.Column('entity_id', sa.BigInteger(), nullable=True))
    
    # Migrate existing PPR journal entries: backfill entity_type and entity_id
    op.execute("""
        UPDATE journal SET 
            entity_type = 'PPR',
            entity_id = ppr_id
        WHERE entity_type IS NULL AND ppr_id IS NOT NULL
    """)
    
    # Make new columns NOT NULL after migration
    op.alter_column('journal', 'entity_type', existing_type=sa.String(50), nullable=False)
    op.alter_column('journal', 'entity_id', existing_type=sa.BigInteger(), nullable=False)
    
    # Make ip column nullable (new entries won't always have it)
    op.alter_column('journal', 'ip', existing_type=sa.String(45), nullable=True)
    
    # Drop the foreign key constraint before dropping the column
    if 'ppr_id' in columns:
        op.drop_constraint('journal_ibfk_1', 'journal', type_='foreignkey')
        op.drop_column('journal', 'ppr_id')
    
    # Add composite index for efficient queries
    op.create_index('idx_entity_lookup', 'journal', ['entity_type', 'entity_id'])
    
    # Drop old index if it exists
    try:
        op.drop_index('idx_ppr_id', table_name='journal')
    except:
        pass
    
    op.create_table('local_flights',
        sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column('registration', sa.String(length=16), nullable=False),
        sa.Column('type', sa.String(length=32), nullable=True),
        sa.Column('callsign', sa.String(length=16), nullable=True),
        sa.Column('pob', sa.Integer(), nullable=False),
        sa.Column('flight_type', sa.Enum('LOCAL', 'CIRCUITS', 'DEPARTURE', name='localflighttype'), nullable=False),
        sa.Column('status', sa.Enum('BOOKED_OUT', 'DEPARTED', 'LANDED', 'CANCELLED', name='localflightstatus'), nullable=False, server_default='BOOKED_OUT'),
        sa.Column('duration', sa.Integer(), nullable=True, comment='Duration in minutes'),
        sa.Column('circuits', sa.Integer(), nullable=True, default=0, comment='Actual number of circuits completed'),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('created_dt', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
        sa.Column('etd', sa.DateTime(), nullable=True),
        sa.Column('departed_dt', sa.DateTime(), nullable=True),
        sa.Column('landed_dt', sa.DateTime(), nullable=True),
        sa.Column('created_by', sa.String(length=16), nullable=True),
        sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4',
        mysql_collate='utf8mb4_unicode_ci'
    )
    
    # Create indexes for local_flights
    op.create_index('idx_registration', 'local_flights', ['registration'])
    op.create_index('idx_flight_type', 'local_flights', ['flight_type'])
    op.create_index('idx_status', 'local_flights', ['status'])
    op.create_index('idx_created_dt', 'local_flights', ['created_dt'])
    op.create_index('idx_etd', 'local_flights', ['etd'])
    op.create_index('idx_created_by', 'local_flights', ['created_by'])
    
    # Create departures table for non-PPR departures to other airports
    op.create_table('departures',
        sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column('registration', sa.String(length=16), nullable=False),
        sa.Column('type', sa.String(length=32), nullable=True),
        sa.Column('callsign', sa.String(length=16), nullable=True),
        sa.Column('pob', sa.Integer(), nullable=False),
        sa.Column('out_to', sa.String(length=64), nullable=False),
        sa.Column('status', sa.Enum('BOOKED_OUT', 'DEPARTED', 'CANCELLED', name='departuresstatus'), nullable=False, server_default='BOOKED_OUT'),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('created_dt', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
        sa.Column('etd', sa.DateTime(), nullable=True),
        sa.Column('departed_dt', sa.DateTime(), nullable=True),
        sa.Column('created_by', sa.String(length=16), nullable=True),
        sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4',
        mysql_collate='utf8mb4_unicode_ci'
    )
    
    op.create_index('idx_dep_registration', 'departures', ['registration'])
    op.create_index('idx_dep_out_to', 'departures', ['out_to'])
    op.create_index('idx_dep_status', 'departures', ['status'])
    op.create_index('idx_dep_created_dt', 'departures', ['created_dt'])
    op.create_index('idx_dep_etd', 'departures', ['etd'])
    op.create_index('idx_dep_created_by', 'departures', ['created_by'])
    
    # Create arrivals table for non-PPR arrivals from elsewhere
    op.create_table('arrivals',
        sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column('registration', sa.String(length=16), nullable=False),
        sa.Column('type', sa.String(length=32), nullable=True),
        sa.Column('callsign', sa.String(length=16), nullable=True),
        sa.Column('pob', sa.Integer(), nullable=False),
        sa.Column('in_from', sa.String(length=64), nullable=False),
        sa.Column('status', sa.Enum('BOOKED_IN', 'LANDED', 'CANCELLED', name='arrivalsstatus'), nullable=False, server_default='BOOKED_IN'),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('created_dt', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
        sa.Column('eta', sa.DateTime(), nullable=True),
        sa.Column('landed_dt', sa.DateTime(), nullable=True),
        sa.Column('created_by', sa.String(length=16), nullable=True),
        sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4',
        mysql_collate='utf8mb4_unicode_ci'
    )
    
    op.create_index('idx_arr_registration', 'arrivals', ['registration'])
    op.create_index('idx_arr_in_from', 'arrivals', ['in_from'])
    op.create_index('idx_arr_status', 'arrivals', ['status'])
    op.create_index('idx_arr_created_dt', 'arrivals', ['created_dt'])
    op.create_index('idx_arr_eta', 'arrivals', ['eta'])
    op.create_index('idx_arr_created_by', 'arrivals', ['created_by'])
    
    # Create circuits table for tracking touch-and-go events during circuit training
    op.create_table('circuits',
        sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column('local_flight_id', sa.BigInteger(), nullable=False),
        sa.Column('circuit_timestamp', sa.DateTime(), nullable=False),
        sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        sa.ForeignKeyConstraint(['local_flight_id'], ['local_flights.id'], ondelete='CASCADE'),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4',
        mysql_collate='utf8mb4_unicode_ci'
    )
    
    # Create indexes for circuits
    op.create_index('idx_circuit_local_flight_id', 'circuits', ['local_flight_id'])
    op.create_index('idx_circuit_timestamp', 'circuits', ['circuit_timestamp'])
    
    # Create overflights table for tracking aircraft talking to the tower but not departing/landing
    op.create_table('overflights',
        sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column('registration', sa.String(length=16), nullable=False),
        sa.Column('pob', sa.Integer(), nullable=True),
        sa.Column('type', sa.String(length=32), nullable=True),
        sa.Column('departure_airfield', sa.String(length=64), nullable=True),
        sa.Column('destination_airfield', sa.String(length=64), nullable=True),
        sa.Column('status', sa.Enum('ACTIVE', 'INACTIVE', 'CANCELLED', name='overflightstatus'), nullable=False, server_default='ACTIVE'),
        sa.Column('call_dt', sa.DateTime(), nullable=False),
        sa.Column('qsy_dt', sa.DateTime(), nullable=True),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('created_dt', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
        sa.Column('created_by', sa.String(length=16), nullable=True),
        sa.Column('updated_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        mysql_engine='InnoDB',
        mysql_charset='utf8mb4',
        mysql_collate='utf8mb4_unicode_ci'
    )
    
    # Create indexes for overflights
    op.create_index('idx_ovf_registration', 'overflights', ['registration'])
    op.create_index('idx_ovf_departure_airfield', 'overflights', ['departure_airfield'])
    op.create_index('idx_ovf_destination_airfield', 'overflights', ['destination_airfield'])
    op.create_index('idx_ovf_status', 'overflights', ['status'])
    op.create_index('idx_ovf_call_dt', 'overflights', ['call_dt'])
    op.create_index('idx_ovf_created_dt', 'overflights', ['created_dt'])
    op.create_index('idx_ovf_created_by', 'overflights', ['created_by'])


def downgrade() -> None:
    """
    Drop the overflights, circuits, arrivals, departures, and local_flights tables.
    """
    op.drop_table('overflights')
    op.drop_table('circuits')
    op.drop_table('arrivals')
    op.drop_table('departures')
    op.drop_table('local_flights')
