// How far ahead must the plan look, and how much work should each solve do?
//
// Runs the swing-up with plans of 0.8 s to 3 s and with one to ten solver iterations per
// stage, and prints when the pendulum was first held inverted. A dash means never in 15 s.
#include <cmath>
#include <cstdio>

#include "pendulum.h"
#include "trace.h"

// The solver's second argument overrides the problem's own number of stages.
template <int Stages>
double swing_up(int iterations, Trace& trace) {
    using Solver = NMPC::Solver<Pendulum, Stages>;
    static typename Solver::Workspace workspace;
    Solver solver(workspace);
    NMPC::Options<double> options;
    options.max_iterations = iterations;
    Pendulum pendulum;
    Pendulum::State x(0.05, 0.0);
    solver.reset(x, Pendulum::Control::Zero());
    double upright_since = -1.0;
    for (int stage = 0; stage < 750; stage++) {
        if (stage > 0) solver.advance(pendulum, 1);
        if (!solver.solve(pendulum, x, options).usable()) return -1.0;
        const bool upright = std::abs(x(0) - kPi) < 0.05 && std::abs(x(1)) < 0.1;
        if (!upright) upright_since = -1.0;
        else if (upright_since < 0.0) upright_since = stage * pendulum.dt;
        if (stage % 2 == 0 && stage < 500) {
            trace.row("run-" + std::to_string(Stages) + "-" + std::to_string(iterations),
                      {stage * pendulum.dt, x(0), solver.policy().u[0](0)});
        }
        x = pendulum.step(0, x, solver.policy().u[0]);
    }
    return upright_since;
}

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const int budgets[] = {1, 2, 5, 10};
    std::printf("plan length   iterations per solve:      1       2       5      10\n");
    const auto row = [&](double seconds, double a, double b, double c, double d) {
        std::printf("%6.1f s                           ", seconds);
        const double times[] = {a, b, c, d};
        for (int i = 0; i < 4; i++) {
            if (times[i] < 0.0) std::printf("       -");
            else std::printf("%6.2f s", times[i]);
            trace.row("upright", {seconds, double(budgets[i]), times[i]});
        }
        std::printf("\n");
    };
    row(0.8, swing_up<40>(1, trace), swing_up<40>(2, trace), swing_up<40>(5, trace), swing_up<40>(10, trace));
    row(1.0, swing_up<50>(1, trace), swing_up<50>(2, trace), swing_up<50>(5, trace), swing_up<50>(10, trace));
    row(1.5, swing_up<75>(1, trace), swing_up<75>(2, trace), swing_up<75>(5, trace), swing_up<75>(10, trace));
    row(2.0, swing_up<100>(1, trace), swing_up<100>(2, trace), swing_up<100>(5, trace), swing_up<100>(10, trace));
    row(3.0, swing_up<150>(1, trace), swing_up<150>(2, trace), swing_up<150>(5, trace), swing_up<150>(10, trace));
    return 0;
}
