// Change what the cost charges for speed and torque, and swing the pendulum up again.
//
//   ./tune <rate weight> [torque weight]
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>

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

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    using Solver = NMPC::Solver<Pendulum>;
    static Solver::Workspace workspace;
    Solver solver(workspace);
    NMPC::Options<double> options;

    Pendulum pendulum;
    if (argc > 1 && argv[1][0] != '-') pendulum.tuning.rate_weight = std::atof(argv[1]);      // default 0.3
    if (argc > 2 && argv[2][0] != '-') pendulum.tuning.torque_weight = std::atof(argv[2]);    // default 0.5

    Pendulum::State x(0.05, 0.0);
    solver.reset(x, Pendulum::Control::Zero());
    double upright_since = -1.0, fastest = 0.0, effort = 0.0;
    for (int stage = 0; stage < 500; stage++) {
        if (stage > 0) solver.advance(pendulum, 1);
        if (!solver.solve(pendulum, x, options).usable()) return 1;
        const Pendulum::Control torque = solver.policy().u[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;
        fastest = std::max(fastest, std::abs(x(1)));
        effort += torque(0) * torque(0) * pendulum.dt;
        if (stage < 300) trace.row("stages", {stage * pendulum.dt, x(0), x(1), torque(0)});
        x = pendulum.step(0, x, torque);
    }

    std::printf("rate weight %.2f, torque weight %.2f: ", pendulum.tuning.rate_weight, pendulum.tuning.torque_weight);
    if (upright_since >= 0.0) std::printf("inverted and still from %.2f s", upright_since);
    else std::printf("never inverted; at %.2f rad after 10 s", x(0));
    std::printf("; fastest %.2f rad/s; torque squared over time %.3f\n", fastest, effort);
    trace.value("upright_since", upright_since);
    trace.value("fastest", fastest);
    trace.value("effort", effort);
    return 0;
}
