#include "datascience/drawdown.h"

namespace fn::ds {

DrawdownResult drawdown_max(const double* equity, std::size_t n) {
    DrawdownResult r{};
    if (equity == nullptr || n == 0) return r;

    double peak = equity[0];
    std::size_t peak_i = 0;
    double max_dd = 0.0;
    std::size_t best_peak_i = 0;
    std::size_t best_trough_i = 0;

    for (std::size_t i = 0; i < n; ++i) {
        double v = equity[i];
        if (v > peak) {
            peak = v;
            peak_i = i;
        } else {
            double dd = peak - v;
            if (dd > max_dd) {
                max_dd = dd;
                best_peak_i = peak_i;
                best_trough_i = i;
            }
        }
    }
    r.max_dd = max_dd;
    r.peak_idx = best_peak_i;
    r.trough_idx = best_trough_i;
    double peak_value = equity[best_peak_i];
    if (peak_value > 0.0) {
        r.max_dd_pct = max_dd / peak_value;
    }
    return r;
}

void drawdown_series(const double* equity, std::size_t n, double* out) {
    if (equity == nullptr || out == nullptr || n == 0) return;
    double peak = equity[0];
    for (std::size_t i = 0; i < n; ++i) {
        if (equity[i] > peak) peak = equity[i];
        out[i] = peak - equity[i];
    }
}

} // namespace fn::ds
