from __future__ import annotations

import math
from itertools import groupby

import numpy as np
import pandas as pd

from psx_signal.config import BacktestConfig, CostConfig


def run_long_only_backtest(
    predictions: pd.DataFrame,
    costs: CostConfig,
    config: BacktestConfig,
) -> tuple[dict[str, float | int], pd.DataFrame]:
    required = {"symbol", "execution_date", "exit_date", "forward_return", "signal"}
    missing = required - set(predictions.columns)
    if missing:
        raise ValueError(f"Missing backtest columns: {', '.join(sorted(missing))}")
    ordered = predictions.dropna(subset=["execution_date", "exit_date", "forward_return"]).sort_values(
        ["execution_date", "symbol"]
    )
    active: dict[str, dict[str, object]] = {}
    trades: list[dict[str, object]] = []
    has_prices = {"entry_open", "exit_close"}.issubset(ordered.columns)

    def close_position(symbol: str, exit_date: pd.Timestamp, exit_price: float, reason: str) -> None:
        position = active.pop(symbol)
        gross_return = exit_price / float(position["entry_price"]) - 1
        net_return = gross_return - costs.round_trip_rate
        trades.append({
            "symbol": symbol, "entry_date": position["entry_date"], "exit_date": exit_date,
            "gross_return": gross_return, "net_return": net_return,
            "allocated_return": net_return * config.position_fraction,
            "position_fraction": config.position_fraction,
            "exit_reason": reason,
        })

    row_columns = ["execution_date", "symbol", "signal", "exit_date", "forward_return"]
    if has_prices:
        row_columns.extend(["entry_open", "exit_close"])
    records = ordered[row_columns].itertuples(index=False, name=None)
    for grouped_date, day_records in groupby(records, key=lambda row: row[0]):
        entry_date = pd.Timestamp(grouped_date)
        daily = list(day_records)
        for symbol, position in list(active.items()):
            if pd.Timestamp(position["exit_date"]) < entry_date:
                close_position(symbol, pd.Timestamp(position["exit_date"]), float(position["exit_price"]), "MAX_HOLD")
        if has_prices:
            for _, symbol, signal, _, _, entry_open, _ in daily:
                if signal in {"SELL", "STRONG SELL"} and symbol in active and pd.notna(entry_open):
                    close_position(symbol, entry_date, float(entry_open), "SELL_SIGNAL")
        for row in daily:
            _, symbol, signal, exit_date, forward_return, *prices = row
            if signal not in {"BUY", "STRONG BUY"}:
                continue
            if symbol in active or len(active) >= config.maximum_concurrent_positions:
                continue
            entry_open, exit_close = prices if has_prices else (None, None)
            entry_price = float(entry_open) if has_prices and pd.notna(entry_open) else 1.0
            exit_price = float(exit_close) if has_prices and pd.notna(exit_close) else 1 + float(forward_return)
            active[symbol] = {
                "entry_date": entry_date, "entry_price": entry_price,
                "exit_date": pd.Timestamp(exit_date), "exit_price": exit_price,
            }
        for symbol, position in list(active.items()):
            if pd.Timestamp(position["exit_date"]) == entry_date:
                close_position(symbol, entry_date, float(position["exit_price"]), "MAX_HOLD")
    for symbol, position in list(active.items()):
        close_position(symbol, pd.Timestamp(position["exit_date"]), float(position["exit_price"]), "MAX_HOLD")
    trade_frame = pd.DataFrame(trades)
    return trading_metrics(trade_frame), trade_frame


def trading_metrics(trades: pd.DataFrame) -> dict[str, float | int]:
    if trades.empty:
        return {"number_of_trades": 0, "total_return": 0.0, "total_return_before_costs": 0.0}
    returns = trades["net_return"].astype(float)
    allocated = trades["allocated_return"].astype(float)
    gross_allocated = trades["gross_return"].astype(float) * trades["position_fraction"].astype(float)
    equity = (1 + allocated).cumprod()
    drawdown = equity / equity.cummax() - 1
    winners = returns[returns > 0]
    losers = returns[returns < 0]
    days = max((trades["exit_date"].max() - trades["entry_date"].min()).days, 1)
    years = days / 365.25
    total_return = float(equity.iloc[-1] - 1)
    std = returns.std(ddof=0)
    downside = returns[returns < 0].std(ddof=0)
    return {
        "number_of_trades": int(len(trades)),
        "total_return": total_return,
        "total_return_before_costs": float((1 + gross_allocated).prod() - 1),
        "annualised_return": float((1 + total_return) ** (1 / years) - 1) if total_return > -1 else -1.0,
        "win_rate": float((returns > 0).mean()),
        "average_trade_return": float(returns.mean()),
        "median_trade_return": float(returns.median()),
        "average_winner": float(winners.mean()) if len(winners) else 0.0,
        "average_loser": float(losers.mean()) if len(losers) else 0.0,
        "profit_factor": float(winners.sum() / abs(losers.sum())) if losers.sum() < 0 else math.inf,
        "maximum_drawdown": float(drawdown.min()),
        "sharpe_ratio": float(returns.mean() / std * np.sqrt(252)) if std else 0.0,
        "sortino_ratio": float(returns.mean() / downside * np.sqrt(252)) if downside else 0.0,
        "average_holding_period": float((trades["exit_date"] - trades["entry_date"]).dt.days.mean()),
        "exposure": float((trades["exit_date"] - trades["entry_date"]).dt.days.sum() / days),
        "turnover": float(len(trades) * 2),
    }
