"""C3 completion: alert thresholds, rule linkage and evidence idempotence."""
from alembic import op
import sqlalchemy as sa

revision = "q2f3g4h5i6j7"
down_revision = "p1e2f3g4h5i6"
branch_labels = None
depends_on = None

def upgrade():
    op.add_column("meter_alert_rules", sa.Column("min_deviation_percent", sa.Float(), nullable=False, server_default="30"))
    op.add_column("meter_alert_rules", sa.Column("low_consumption_threshold", sa.Float(), nullable=True))
    op.add_column("meter_alerts", sa.Column("rule_id", sa.Integer(), nullable=True))
    op.create_foreign_key("fk_meter_alerts_rule_id", "meter_alerts", "meter_alert_rules", ["rule_id"], ["id"], ondelete="SET NULL")
    op.create_index("ix_meter_alerts_rule_id", "meter_alerts", ["rule_id"])
    op.create_unique_constraint("uq_meter_alert_evidence_interval", "meter_alert_evidence", ["alert_id", "reading_start_id", "reading_end_id"])

def downgrade():
    op.drop_constraint("uq_meter_alert_evidence_interval", "meter_alert_evidence", type_="unique")
    op.drop_index("ix_meter_alerts_rule_id", table_name="meter_alerts")
    op.drop_constraint("fk_meter_alerts_rule_id", "meter_alerts", type_="foreignkey")
    op.drop_column("meter_alerts", "rule_id")
    op.drop_column("meter_alert_rules", "low_consumption_threshold")
    op.drop_column("meter_alert_rules", "min_deviation_percent")
