// Website benchmark harness: the native QuantLib counterpart of
// crates/morphiq-risk/examples/website_harness.rs, with the same fixtures, the
// same timing protocol (pilot-sized ~50 ms samples, one second of warmup, 60
// samples, median per call) and the same JSON shape. Every timed call forces
// recalculation, so cached results are never measured.
#include <ql/quantlib.hpp>

#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace QuantLib;
using Clock = std::chrono::steady_clock;

namespace {

const char* kUsage = "usage: quantlib_harness [--samples N] [--target-ms N] [--warmup-ms N]";
const uint64_t kIvQuoteBits = 0x40397df98ba57cc1ULL;

struct Protocol {
    int samples = 60;
    long target_ms = 50;
    long warmup_ms = 1000;
};

double from_bits(uint64_t bits) {
    double value;
    std::memcpy(&value, &bits, sizeof value);
    return value;
}

std::string hex(double value) {
    uint64_t bits;
    std::memcpy(&bits, &value, sizeof bits);
    char text[17];
    std::snprintf(text, sizeof text, "%016llx", static_cast<unsigned long long>(bits));
    return text;
}

std::string number(double value) {
    std::ostringstream out;
    out.precision(17);
    out << value;
    return out.str();
}

volatile double sink = 0.0;

std::string measure(const Protocol& protocol, const std::function<double()>& call) {
    const int pilot = 64;
    auto start = Clock::now();
    for (int i = 0; i < pilot; ++i) sink = sink + call();
    double per_call = std::max<double>(1.0, std::chrono::duration<double, std::nano>(Clock::now() - start).count()) / pilot;
    auto iterations = static_cast<long long>(std::max(1.0, std::ceil(protocol.target_ms * 1e6 / per_call)));
    auto warm = Clock::now();
    while (Clock::now() - warm < std::chrono::milliseconds(protocol.warmup_ms)) sink = sink + call();
    std::vector<long long> elapsed;
    std::vector<double> per;
    for (int s = 0; s < protocol.samples; ++s) {
        auto t0 = Clock::now();
        for (long long i = 0; i < iterations; ++i) sink = sink + call();
        auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - t0).count();
        elapsed.push_back(ns);
        per.push_back(static_cast<double>(ns) / iterations);
    }
    std::sort(per.begin(), per.end());
    double median = per.size() % 2 ? per[per.size() / 2] : (per[per.size() / 2 - 1] + per[per.size() / 2]) / 2.0;
    std::ostringstream out;
    out << "{\"iterations\": " << iterations << ", \"elapsed_ns\": [";
    for (size_t i = 0; i < elapsed.size(); ++i) out << (i ? ", " : "") << elapsed[i];
    out << "], \"median_ns\": " << number(median) << "}";
    return out.str();
}

struct Contract {
    ext::shared_ptr<GeneralizedBlackScholesProcess> process;
    ext::shared_ptr<StrikedTypePayoff> payoff;
    ext::shared_ptr<Exercise> exercise;
    std::string inputs_json;
    // One option per engine, so no engine shares another's cached state.
    ext::shared_ptr<VanillaOption> with(const ext::shared_ptr<PricingEngine>& engine) const {
        auto option = ext::make_shared<VanillaOption>(payoff, exercise);
        option->setPricingEngine(engine);
        return option;
    }
};

Contract contract(const Date& today, Option::Type type, bool american, double spot, double strike,
                  int days, double years, double rate, double yield, double vol) {
    DayCounter dc = Actual360();
    Date maturity = today + days;
    QL_REQUIRE(dc.yearFraction(today, maturity) == years, "expiry does not reproduce the fixture's years");
    auto process = ext::make_shared<BlackScholesMertonProcess>(
        Handle<Quote>(ext::make_shared<SimpleQuote>(spot)),
        Handle<YieldTermStructure>(ext::make_shared<FlatForward>(today, yield, dc)),
        Handle<YieldTermStructure>(ext::make_shared<FlatForward>(today, rate, dc)),
        Handle<BlackVolTermStructure>(ext::make_shared<BlackConstantVol>(today, NullCalendar(), vol, dc)));
    ext::shared_ptr<Exercise> exercise = american
        ? ext::shared_ptr<Exercise>(ext::make_shared<AmericanExercise>(today, maturity))
        : ext::shared_ptr<Exercise>(ext::make_shared<EuropeanExercise>(maturity));
    std::ostringstream in;
    in << "{\"option_type\": \"" << (type == Option::Call ? "Call" : "Put") << "\", \"exercise_style\": \""
       << (american ? "American" : "European") << "\", \"days_actual_360\": " << days
       << ", \"spot_strike_time_rate_yield_volatility_bits\": [\"" << hex(spot) << "\", \"" << hex(strike)
       << "\", \"" << hex(years) << "\", \"" << hex(rate) << "\", \"" << hex(yield) << "\", \"" << hex(vol) << "\"]}";
    return {process, ext::make_shared<PlainVanillaPayoff>(type, strike), exercise, in.str()};
}

double price(VanillaOption& option) {
    option.recalculate();
    return option.NPV();
}

double greeks5(VanillaOption& option) {
    option.recalculate();
    return option.NPV() + option.delta() + option.gamma() + option.vega() + option.theta() + option.rho();
}

std::string greek_values(VanillaOption& option) {
    option.recalculate();
    std::ostringstream out;
    out << "[" << number(option.NPV()) << ", " << number(option.delta()) << ", " << number(option.gamma()) << ", "
        << number(option.vega()) << ", " << number(option.theta()) << ", " << number(option.rho()) << "]";
    return out.str();
}

}  // namespace

int main(int argc, char** argv) {
    std::vector<std::string> args(argv + 1, argv + argc);
    for (const auto& a : args) {
        if (a == "--help" || a == "-h") { std::cout << kUsage << "\n"; return 0; }
        if (a == "--version") { std::cout << "quantlib_harness 1 (QuantLib " << QL_VERSION << ")\n"; return 0; }
    }
    Protocol protocol;
    for (size_t i = 0; i < args.size() && args[i] != "--"; i += 2) {
        if (i + 1 >= args.size()) { std::cerr << args[i] << " needs a value\n" << kUsage << "\n"; return 2; }
        long value = std::stol(args[i + 1]);
        if (args[i] == "--samples") protocol.samples = static_cast<int>(value);
        else if (args[i] == "--target-ms") protocol.target_ms = value;
        else if (args[i] == "--warmup-ms") protocol.warmup_ms = value;
        else { std::cerr << "unknown argument " << args[i] << "\n" << kUsage << "\n"; return 2; }
    }
    if (protocol.samples <= 0) { std::cerr << "--samples must be positive\n"; return 2; }

    Date today(9, September, 2026);
    Settings::instance().evaluationDate() = today;
    Contract eu = contract(today, Option::Call, false, 120.0, 100.0, 270, 0.75, 0.03, 0.01, 0.32);
    Contract am = contract(today, Option::Put, true, 100.0, 105.0, 180, 0.5, 0.03, 0.01, 0.25);
    auto european = eu.with(ext::make_shared<AnalyticEuropeanEngine>(eu.process));
    auto bs93 = am.with(ext::make_shared<BjerksundStenslandApproximationEngine>(am.process));
    struct Scheme { const char* name; ext::shared_ptr<QdFpIterationScheme> scheme; };
    std::vector<Scheme> schemes = {{"fast", QdFpAmericanEngine::fastScheme()},
                                   {"accurate", QdFpAmericanEngine::accurateScheme()},
                                   {"high_precision", QdFpAmericanEngine::highPrecisionScheme()}};
    std::vector<ext::shared_ptr<VanillaOption>> qdfp;
    for (const auto& s : schemes) qdfp.push_back(am.with(ext::make_shared<QdFpAmericanEngine>(am.process, s.scheme)));
    const double quote = from_bits(kIvQuoteBits);
    auto iv = [&] { return european->impliedVolatility(quote, eu.process, 1e-10, 100, 1e-7, 4.0); };

    std::ostringstream outputs, timings;
    outputs << "{\"european_price\": " << number(price(*european)) << ", \"european_iv\": " << number(iv())
            << ", \"european_greeks5\": " << greek_values(*european)
            << ", \"american_bs1993_price\": " << number(price(*bs93))
            << ", \"american_bs1993_greeks5\": " << greek_values(*bs93);
    for (size_t i = 0; i < schemes.size(); ++i)
        outputs << ", \"american_qdfp_" << schemes[i].name << "_price\": " << number(price(*qdfp[i]));
    outputs << "}";
    timings << "{\"european_price\": " << measure(protocol, [&] { return price(*european); })
            << ", \"european_iv\": " << measure(protocol, iv)
            << ", \"european_greeks5\": " << measure(protocol, [&] { return greeks5(*european); })
            << ", \"american_bs1993_price\": " << measure(protocol, [&] { return price(*bs93); })
            << ", \"american_bs1993_greeks5\": " << measure(protocol, [&] { return greeks5(*bs93); });
    for (size_t i = 0; i < schemes.size(); ++i)
        timings << ", \"american_qdfp_" << schemes[i].name << "_price\": "
                << measure(protocol, [&, i] { return price(*qdfp[i]); });
    timings << "}";

    std::cout << "{\n\"harness\": \"quantlib_harness 1\", \"engine\": \"QuantLib\", \"engine_version\": \"" << QL_VERSION
              << "\",\n\"protocol\": {\"samples\": " << protocol.samples << ", \"target_ms\": " << protocol.target_ms
              << ", \"warmup_ms\": " << protocol.warmup_ms << ", \"statistic\": \"median ns per call\"},\n"
              << "\"result\": {\"group\": \"scalar\", \"evaluation_date\": \"2026-09-09\", \"day_counter\": \"Actual/360\", "
              << "\"inputs\": {\"european\": " << eu.inputs_json << ", \"american\": " << am.inputs_json
              << ", \"iv_quote_bits\": \"" << hex(quote) << "\", \"iv_solver\": {\"accuracy\": 1e-10, \"max_evaluations\": 100, "
              << "\"min_vol\": 1e-7, \"max_vol\": 4.0}},\n"
              << "\"greek_order\": [\"price\", \"delta\", \"gamma\", \"vega\", \"theta_per_year\", \"rho\"],\n"
              << "\"outputs\": " << outputs.str() << ",\n\"timings\": " << timings.str() << "}\n}\n";
    return 0;
}
