"""Enforce singleton score and fundamental snapshots.

Revision ID: 019
Revises: 018
Create Date: 2026-07-11 00:00:00.000000
"""

from __future__ import annotations

from alembic import op
import sqlalchemy as sa


revision = "019"
down_revision = "018"
branch_labels = None
depends_on = None


def _remove_duplicates(table: str, partition_by: str, order_by: str) -> None:
    op.execute(
        sa.text(
            f"""
            DELETE FROM {table}
            WHERE id IN (
                SELECT id FROM (
                    SELECT id, ROW_NUMBER() OVER (
                        PARTITION BY {partition_by}
                        ORDER BY {order_by} DESC, id DESC
                    ) AS row_number
                    FROM {table}
                ) AS ranked
                WHERE row_number > 1
            )
            """
        )
    )


def upgrade() -> None:
    _remove_duplicates("dimension_scores", "ticker_id, dimension", "computed_at")
    _remove_duplicates("composite_scores", "ticker_id", "computed_at")
    _remove_duplicates("fundamental_data", "ticker_id", "fetched_at")

    op.create_unique_constraint(
        "uq_dimension_score_ticker_dimension",
        "dimension_scores",
        ["ticker_id", "dimension"],
    )
    op.create_unique_constraint("uq_composite_score_ticker", "composite_scores", ["ticker_id"])
    op.create_unique_constraint("uq_fundamental_data_ticker", "fundamental_data", ["ticker_id"])
    op.create_index("ix_sr_levels_ticker_id", "sr_levels", ["ticker_id"])
    op.create_index("ix_trade_setups_ticker_rr", "trade_setups", ["ticker_id", "rr_ratio"])


def downgrade() -> None:
    op.drop_index("ix_trade_setups_ticker_rr", table_name="trade_setups")
    op.drop_index("ix_sr_levels_ticker_id", table_name="sr_levels")
    op.drop_constraint("uq_fundamental_data_ticker", "fundamental_data", type_="unique")
    op.drop_constraint("uq_composite_score_ticker", "composite_scores", type_="unique")
    op.drop_constraint("uq_dimension_score_ticker_dimension", "dimension_scores", type_="unique")
