# reproduce/core/drl_comparator.py
"""DRL inference comparison: reproduce output vs SR_analysis reference.

For each scene, loads the reproduce output (sensors/forces/actions) and
compares against SR_analysis reference controlled.npz.
"""

from __future__ import annotations

import json
import os
import sys
from typing import Dict, Optional

import numpy as np

_REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", ".."))
_SRC = os.path.join(_REPO, "src")
for p in [_REPO, _SRC]:
    if p not in sys.path:
        sys.path.insert(0, p)

from legacy_test.core.comparator import (  # noqa: E402
    compare_scene,
    pearson_corr, dtw_similarity, rms_error,
)


def compare_reproduce_output(
    ref_dir: str,
    output_dir: str,
    label: str = "",
    conv_len: int = 30,
) -> Dict:
    """Load reproduce output and compare against SR_analysis reference.

    Args:
        ref_dir: Path to SR_analysis scene directory.
        output_dir: Path to reproduce output directory.
        label: Scene label for printing.
        conv_len: DTW convergence window length.

    Returns:
        dict with comparison metrics (same schema as compare_scene).
    """
    signals_path = os.path.join(output_dir, "signals.npz")
    if not os.path.isfile(signals_path):
        raise FileNotFoundError(f"Reproduce output not found: {signals_path}")

    data = np.load(signals_path)
    sensors = np.asarray(data["sensors"], dtype=np.float32)
    forces = np.asarray(data["forces"], dtype=np.float32)
    actions = np.asarray(data["actions"], dtype=np.float32)

    return compare_scene(
        ref_dir, sensors, forces, actions,
        conv_len=conv_len, label=label,
    )
