from __future__ import annotations

import numpy as np
import pandas as pd


def add_forward_labels(
    frame: pd.DataFrame,
    horizons: tuple[int, ...] = (1, 5),
    buy_threshold: float = 0.01,
    sell_threshold: float = -0.01,
) -> pd.DataFrame:
    """Labels at T use entry OPEN[T+1] and exit CLOSE[T+horizon] within each symbol."""
    if sell_threshold >= buy_threshold:
        raise ValueError("sell_threshold must be below buy_threshold")

    def per_symbol(group: pd.DataFrame) -> pd.DataFrame:
        result = group.sort_values("date").copy()
        raw_entry_open = result["open"].shift(-1)
        adjusted_entry = (
            result["adjusted_open"].combine_first(result["open"]).shift(-1)
            if "adjusted_open" in result else raw_entry_open
        )
        adjusted_exit = (
            result["adjusted_close"].combine_first(result["close"])
            if "adjusted_close" in result else result["close"]
        )
        execution_date = result["date"].shift(-1)
        for horizon in horizons:
            forward_return = adjusted_exit.shift(-horizon) / adjusted_entry - 1
            result[f"execution_date_{horizon}d"] = execution_date
            result[f"exit_date_{horizon}d"] = result["date"].shift(-horizon)
            result[f"entry_open_{horizon}d"] = raw_entry_open
            result[f"exit_close_{horizon}d"] = result["close"].shift(-horizon)
            result[f"forward_return_{horizon}d"] = forward_return
            label = np.select(
                [forward_return >= buy_threshold, forward_return <= sell_threshold],
                [1, -1], default=0,
            )
            result[f"label_{horizon}d"] = pd.Series(label, index=result.index, dtype="Int8").where(forward_return.notna())
        return result

    return (
        frame.sort_values(["symbol", "date"])
        .groupby("symbol", group_keys=False, sort=False)
        .apply(per_symbol, include_groups=False)
        .reset_index(drop=True)
        .assign(symbol=lambda data: frame.sort_values(["symbol", "date"])["symbol"].to_numpy())
        .sort_values(["date", "symbol"])
        .reset_index(drop=True)
    )
