// Swing up a pendulum whose weight differs from the one in the controller's model.
//
//   ./track <direct|track> <real mass / modelled mass>
//
// direct: each solve starts from the measured state, and the motor applies the plan's first
//         torque. The plan may use the whole 0.35 N m.
// track:  the plan may use 0.30 N m and advances on its own prediction. Every millisecond an
//         attitude and rate cascade spends what is left on holding the real pendulum to the plan.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "NMPC/InnerLoop.h"
#include "pendulum.h"
#include "trace.h"

using Vector3 = NMPC::Vector<double, 3>;

// The pendulum's angle as a rotation about the motor shaft, which the cascade expects.
NMPC::Quaternion<double> about_shaft(double angle) {
    return NMPC::so3_exp<double>(Vector3(0.0, 0.0, angle));
}

int main(int argc, char** argv) {
    Trace trace(argc, argv);
    const bool tracking = argc > 1 ? std::strcmp(argv[1], "track") == 0 : true;
    const double mass_scale = argc > 2 && argv[2][0] != '-' ? std::atof(argv[2]) : 0.95;

    using Solver = NMPC::Solver<Pendulum>;
    static Solver::Workspace workspace;
    Solver solver(workspace);
    NMPC::Options<double> options;

    const double motor_limit = 0.35;                 // what the motor can deliver, N m
    const double reserve = tracking ? 0.05 : 0.0;    // kept back for the inner loop
    Pendulum model;
    model.substeps = 20;
    model.tuning.torque_limit = motor_limit - reserve;  // control_bounds gives the plan the rest

    Pendulum real;  // the simulated pendulum, with a different weight on the rod
    real.tuning.mass = mass_scale * model.tuning.mass;

    NMPC::AttitudeCascade<double> cascade;
    cascade.k_attitude = Vector3::Constant(6.0);   // rad/s of rate asked per rad of angle error
    cascade.kp = Vector3::Constant(18.0);          // rad/s^2 per rad/s of rate error
    cascade.ki = Vector3::Constant(40.0);
    cascade.kd = Vector3::Zero();
    cascade.integral_limit = Vector3::Constant(reserve);
    cascade.design(0.001);                         // the inner loop's tick, s
    const Vector3 inertia = Vector3::Constant(model.inertia());

    Pendulum::State x(0.05, 0.0);  // the real pendulum
    Pendulum::State planned = x;   // where the plan says it should be at this tick
    solver.reset(x, Pendulum::Control::Zero());

    double upright_since = -1.0, worst = 0.0;
    for (int stage = 0; stage < 500; stage++) {
        if (stage > 0) solver.advance(model, 1);
        if (!tracking) planned = x;  // direct: plan again from where the pendulum really is
        if (!solver.solve(model, planned, options).usable()) return 1;
        const double plan_torque = solver.policy().u[0](0);

        const Pendulum::State at_solve = x, planned_at_solve = planned;
        double applied_sum = 0.0;
        for (int tick = 0; tick < 20; tick++) {
            double torque = plan_torque;
            bool clipped = false;
            if (tracking) {
                const Vector3 moment = cascade.moment(about_shaft(x(0)), Vector3(0.0, 0.0, x(1)),
                                                      about_shaft(planned(0)), Vector3(0.0, 0.0, planned(1)), inertia);
                const double wanted = plan_torque + moment.z();
                torque = std::clamp(wanted, -motor_limit, motor_limit);
                clipped = torque != wanted;
                cascade.integrate(clipped, inertia);  // the integral waits while the motor is at its limit
            }
            const double from_top = std::remainder(x(0) - kPi, 2.0 * kPi);
            const bool upright = std::abs(from_top) < 0.05 && std::abs(x(1)) < 0.1;
            if (!upright) upright_since = -1.0;
            else if (upright_since < 0.0) upright_since = stage * model.dt + tick * 0.001;
            worst = std::max(worst, std::abs(x(0) - planned(0)));

            x = real.substep(x, torque, 0.001);                    // what happens
            planned = model.substep(planned, plan_torque, 0.001);  // what the model expects
            applied_sum += torque;
        }
        if (stage % 2 == 0 && stage < 350) {
            trace.row("stages", {stage * model.dt, at_solve(0), at_solve(1), plan_torque, planned_at_solve(0),
                                 applied_sum / 20.0});
        }
    }

    std::printf("%s, weight %+.0f%%: ", tracking ? "plan and track" : "direct", 100.0 * (mass_scale - 1.0));
    if (upright_since >= 0.0) std::printf("inverted and still from %.2f s", upright_since);
    else std::printf("not held inverted within 10 s");
    if (tracking) std::printf("; never more than %.3f rad from the plan", worst);
    std::printf("\n");
    trace.value("upright_since", upright_since);
    trace.value("worst", worst);
    return 0;
}
