"""Versioned similarity metrics shared by validation and data export."""
from __future__ import annotations

from typing import Any

import numpy as np

LEGACY_DTW_VERSION = "legacy_dtw_v1_abs_n_unclipped"


def legacy_cycle_similarity(
    target: np.ndarray,
    state: np.ndarray,
    conv_len: int,
    *,
    lag_channel: int = 1,
) -> dict[str, Any]:
    """Compare one target reference cycle with the final controlled cycle."""
    from SR_analysis.utils.cfd_interface import calc_dtw_sim, calc_lag

    target_array = np.asarray(target, dtype=np.float64)
    state_array = np.asarray(state, dtype=np.float64)
    if target_array.ndim != 2 or target_array.shape[1] != 6:
        raise ValueError(f"legacy metric target must have shape (n, 6), got {target_array.shape}")
    if state_array.ndim != 2 or state_array.shape[1] != 6:
        raise ValueError(f"legacy metric state must have shape (n, 6), got {state_array.shape}")
    if conv_len <= 0:
        raise ValueError(f"conv_len must be positive, got {conv_len}")
    if not 0 <= lag_channel < 6:
        raise ValueError(f"lag_channel must be in [0, 5], got {lag_channel}")
    if len(target_array) < 2 * conv_len or len(state_array) < conv_len:
        raise ValueError(
            f"legacy metric requires target >= {2 * conv_len} and state >= {conv_len} samples"
        )

    target_window = target_array[conv_len : 2 * conv_len, lag_channel]
    state_window = state_array[-conv_len:, lag_channel]
    lag = calc_lag(target_window, state_window)
    scores = [
        float(
            calc_dtw_sim(
                np.roll(target_array[:, index], -lag)[conv_len : 2 * conv_len],
                state_array[-conv_len:, index],
            )
        )
        for index in range(6)
    ]
    return {
        "similarity": float(np.mean(scores)),
        "per_channel": {str(index): score for index, score in enumerate(scores)},
        "lag": int(lag),
    }
