#pragma once
#include "types.hpp"
#include "custom_strategy.hpp"
#include "risk.hpp"
#include <vector>
#include <deque>
#include <string>
#include <cstdio>
#include <cmath>
#include <fstream>
#include <sstream>

namespace quant {

// 回测成交(撮合记录)
struct BacktestTrade {
    int64_t entry_ts = 0;
    double entry_price = 0.0;
    double qty = 0.0;
    uint8_t side = 0;         // 0=long, 1=short
    int64_t exit_ts = 0;
    double exit_price = 0.0;
    double pnl = 0.0;         // 已实现盈亏(含手续费)
    bool closed = false;
};

// 回测统计
struct BacktestStats {
    size_t bars = 0;
    size_t trades = 0;        // 已平仓交易数
    double initial_capital = 0.0;
    double final_capital = 0.0;
    double total_return_pct = 0.0;   // 总收益率 %
    double max_drawdown_pct = 0.0;   // 最大回撤 %
    double sharpe = 0.0;             // 夏普(年化,无风险=0)
    double win_rate = 0.0;           // 胜率 %
    double avg_win = 0.0, avg_loss = 0.0;
    double profit_factor = 0.0;      // 盈亏比
    size_t long_trades = 0, short_trades = 0;
};

// 回测引擎:喂历史 K 线回放策略,策略零修改
class Backtester {
public:
    struct Config {
        double initial_capital = 10000.0;
        double fee_rate = 0.0005;     // 单边手续费 0.05%
        double slippage = 0.0002;     // 滑点 0.02%
        RiskConfig risk;              // 复用风控(仓位、止损)
    };

    Backtester(Strategy& strategy, Config cfg) : strategy_(strategy), cfg_(std::move(cfg)) {}

    // 回放一批 K 线(同一 symbol 的历史,时间升序)
    BacktestStats run(const std::vector<Kline>& bars, const Symbol& symbol) {
        stats_ = {};
        stats_.initial_capital = cfg_.initial_capital;
        stats_.final_capital = cfg_.initial_capital;
        RiskManager risk(cfg_.risk, cfg_.initial_capital);
        std::vector<BacktestTrade> trades;
        double peak = cfg_.initial_capital;
        double eq_curve_sum = 0.0, eq_curve_sq = 0.0;
        std::vector<double> returns;
        size_t n = bars.size();
        stats_.bars = n;
        size_t wins = 0, losses = 0;
        double total_win = 0.0, total_loss = 0.0;

        // 策略信号回调:记录信号,撮合在下一根 bar 开盘(避免前视)
        Signal pending{};
        bool has_pending = false;
        strategy_.set_signal_callback([&](const Signal& sig) {
            pending = sig;
            has_pending = true;
        });

        for (size_t i = 0; i < n; ++i) {
            const Kline& k = bars[i];

            // 1) 若有上一根信号 → 用当前 bar 开盘价撮合(下一根开盘执行)
            if (has_pending && i > 0) {
                double exec_price = bars[i].open * (1.0 + cfg_.slippage * ((pending.side <= 1) ? 1 : -1));
                if (pending.side <= 1) {
                    // 开仓:多头或空头
                    double atr = exec_price * 0.002;
                    double qty = risk.calculate_position_size(atr, exec_price);
                    if (qty > 0 && risk.check_pre_trade(OrderRequest{}, exec_price)) {
                        trades.push_back({bars[i].timestamp, exec_price, qty, (uint8_t)pending.side});
                    }
                } else {
                    // 平仓:找到最后未平仓的同向交易
                    for (auto it = trades.rbegin(); it != trades.rend(); ++it) {
                        if (!it->closed) {
                            uint8_t close_side = (pending.side == 2) ? 0 : 1;
                            if (close_side == it->side) {
                                it->exit_ts = bars[i].timestamp;
                                it->exit_price = exec_price;
                                double pnl = (it->exit_price - it->entry_price) * it->qty;
                                if (it->side == 1) pnl = -pnl;
                                double fee = (it->entry_price * it->qty + it->exit_price * it->qty) * cfg_.fee_rate;
                                it->pnl = pnl - fee;
                                it->closed = true;
                                stats_.final_capital += it->pnl;
                                ++stats_.trades;
                                if (it->side == 0) ++stats_.long_trades; else ++stats_.short_trades;
                                if (it->pnl > 0) { ++wins; total_win += it->pnl; }
                                else { ++losses; total_loss += it->pnl; }
                                break;
                            }
                        }
                    }
                }
                has_pending = false;
            }

            // 2) 喂策略(只喂历史,让策略算指标)
            strategy_.on_kline(k);

            // 3) 更新权益曲线(按当前价未实现 + 已实现)
            double eq = stats_.final_capital;
            for (const auto& t : trades) {
                if (!t.closed) {
                    double upnl = (k.close - t.entry_price) * t.qty;
                    if (t.side == 1) upnl = -upnl;
                    eq += upnl;
                }
            }
            double ret = (eq - peak) / peak;
            if (eq > peak) peak = eq;
            if (ret < 0) stats_.max_drawdown_pct = std::max(stats_.max_drawdown_pct, -ret * 100.0);
            if (i > 0) returns.push_back((eq - stats_.final_capital) / stats_.final_capital);
            eq_curve_sum += eq;
            eq_curve_sq += eq * eq;
        }

        // 统计
        stats_.total_return_pct = (stats_.final_capital - stats_.initial_capital) / stats_.initial_capital * 100.0;
        if (stats_.trades > 0) {
            stats_.win_rate = (double)wins / stats_.trades * 100.0;
            stats_.avg_win = (wins > 0) ? total_win / wins : 0.0;
            stats_.avg_loss = (losses > 0) ? total_loss / losses : 0.0;
            stats_.profit_factor = (total_loss < 0.0) ? (total_win / -total_loss) : 0.0;
        }
        // 夏普(按 bar 收益,年化=sqrt(bar_per_year) 简化用 252*24*4)
        if (returns.size() > 2) {
            double mean = 0.0, sd = 0.0;
            for (double r : returns) mean += r;
            mean /= returns.size();
            for (double r : returns) sd += (r - mean) * (r - mean);
            sd = std::sqrt(sd / returns.size());
            if (sd > 0) stats_.sharpe = mean / sd * std::sqrt(252.0 * 24.0 * 4.0); // 15m bar
        }
        return stats_;
    }

    const BacktestStats& stats() const { return stats_; }

private:
    Strategy& strategy_;
    Config cfg_;
    BacktestStats stats_;
};

// ---------- CSV 读取:OKX K线格式 [ts,open,high,low,close,vol,...] ----------
// 每行: ts,open,high,low,close,volume(秒或毫秒时间戳均可)
inline std::vector<Kline> load_klines_csv(const std::string& path) {
    std::vector<Kline> out;
    std::ifstream f(path);
    if (!f) return out;
    std::string line;
    std::getline(f, line);  // header
    while (std::getline(f, line)) {
        if (line.empty()) continue;
        std::stringstream ss(line);
        std::string tok;
        std::vector<std::string> parts;
        while (std::getline(ss, tok, ',')) parts.push_back(tok);
        if (parts.size() < 6) continue;
        double ts = std::strtod(parts[0].c_str(), nullptr);
        Kline k{};
        k.timestamp = (int64_t)ts;
        k.open = std::strtod(parts[1].c_str(), nullptr);
        k.high = std::strtod(parts[2].c_str(), nullptr);
        k.low = std::strtod(parts[3].c_str(), nullptr);
        k.close = std::strtod(parts[4].c_str(), nullptr);
        k.volume = std::strtod(parts[5].c_str(), nullptr);
        out.push_back(k);
    }
    return out;
}

} // namespace quant