"""Update 'chk_ai_config_algorithm_type' constraint

Split anomaly_zscore into anomaly_zscore_meter and anomaly_zscore_sensor.

Revision ID: 0f438854f378
Revises: 436c6f3e5e82
Create Date: 2026-02-26 14:10:15.945527

"""

from typing import Sequence, Union

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "0f438854f378"
down_revision: Union[str, None] = "436c6f3e5e82"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Drop old constraint first (required before updating data)
    op.drop_constraint("chk_ai_config_algorithm_type", "ai_analysis_config")

    # Update existing records with old algorithm type
    op.execute(
        """
        UPDATE ai_analysis_config
        SET algorithm_type = 'anomaly_zscore_meter'
        WHERE algorithm_type = 'anomaly_zscore'
    """
    )

    # Create new constraint with updated algorithm types
    op.create_check_constraint(
        "chk_ai_config_algorithm_type",
        "ai_analysis_config",
        "algorithm_type IN ('anomaly_zscore_meter', 'anomaly_zscore_sensor', "
        "'anomaly_iqr', 'leak_detection', 'isolation_forest', "
        "'correlation_analysis', 'lstm_autoencoder', 'prophet_forecast')",
    )


def downgrade() -> None:
    # Drop new constraint
    op.drop_constraint("chk_ai_config_algorithm_type", "ai_analysis_config")

    # Revert records back to old algorithm type
    op.execute(
        """
        UPDATE ai_analysis_config
        SET algorithm_type = 'anomaly_zscore'
        WHERE algorithm_type IN ('anomaly_zscore_meter', 'anomaly_zscore_sensor')
    """
    )

    # Recreate old constraint
    op.create_check_constraint(
        "chk_ai_config_algorithm_type",
        "ai_analysis_config",
        "algorithm_type IN ('anomaly_zscore', 'anomaly_iqr', 'leak_detection', "
        "'isolation_forest', 'correlation_analysis', 'lstm_autoencoder', "
        "'prophet_forecast')",
    )
