// The two-rate loop of the policy chapter. The solver runs once per stage (20 ms) or less
// often. In between, an inner loop applies the solver's plan to the simulated pendulum every
// millisecond.
//
// policy.cpp taps the pendulum in this loop and measures what happens. The figure in the
// chapter runs the same loop in the browser.
#ifndef GUIDE_LOOP_H
#define GUIDE_LOOP_H

#include <algorithm>
#include <cmath>

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

struct Loop {
    using Solver = NMPC::Solver<Pendulum>;
    using Plan = NMPC::Policy<Pendulum>;

    // The four loops the chapter compares, and how often the solver runs.
    bool feedback = true;        // between solves, correct the plan's torque with its stored gain
    bool from_measured = false;  // start each solve from the measured state, not the plan's prediction
    int period = 1;              // stages between solves

    static constexpr long ticks_per_stage = 20;  // inner-loop ticks of 1 ms in one 20 ms stage

    Pendulum pendulum;
    NMPC::Options<double> options;
    Solver solver;
    // The inner loop reads its own copy of the plan, stamped with the tick at which it starts.
    Plan plan;

    long tick = 0;
    Pendulum::State x;          // the simulated pendulum
    Pendulum::State predicted;  // where the plan expects the pendulum to be now
    Pendulum::Control torque;   // what the motor applies during this tick
    Pendulum::Control planned;  // what the plan alone asks for during this tick
    Plan::Gain gain;            // the stored gain of the stage in force
    Pendulum::Control lower, upper;

    explicit Loop(Solver::Workspace& workspace) : solver(workspace) {
        pendulum.substeps = 20;  // the model takes the same 1 ms steps as the simulated pendulum
        pendulum.control_bounds(0, lower, upper);
        reset();
    }

    double tick_s() const { return pendulum.dt / ticks_per_stage; }

    // Stand the pendulum inverted and at rest, with a plan that applies no torque.
    void reset() {
        tick = 0;
        x = Pendulum::State(kPi, 0.0);
        predicted = x;
        torque.setZero();
        planned.setZero();
        gain.setZero();
        solver.reset(x, Pendulum::Control::Zero());
    }

    // Work out the torque for this tick, solving first if a solve is due. Returns false if the
    // solver could not produce a usable plan.
    bool command() {
        if (tick % (period * ticks_per_stage) == 0) {
            if (tick > 0) solver.advance(pendulum, period);
            const Pendulum::State start = from_measured ? x : predicted;
            if (!solver.solve(pendulum, start, options).usable()) return false;
            plan = solver.policy();  // a copy of every stage's state, torque and gain
            plan.origin = tick;
            plan.ticks_per_stage = ticks_per_stage;
        }

        const auto stage = plan.at(tick);  // the stage in force at this tick
        if ((tick - plan.origin) % ticks_per_stage == 0) predicted = stage.x;
        planned = stage.u;
        torque = planned;
        if (feedback) torque = plan.feedback(stage.index, x, predicted);  // u + K * (x - predicted)
        torque = NMPC::clamp(torque, lower, upper);
        gain = stage.K;
        return true;
    }

    // Move on by one millisecond under the torque that command() chose.
    void advance() {
        x = pendulum.substep(x, torque(0), tick_s());                   // the pendulum itself
        predicted = pendulum.substep(predicted, planned(0), tick_s());  // the plan's own prediction
        tick++;
    }
};

// What became of a tap: how far the rod got from inverted, and when it was at rest there again.
struct Recovery {
    double peak = 0.0;      // rad from inverted
    double at_rest = -1.0;  // seconds after the tap, or negative while the rod is not at rest

    // Call at every tick from the tap on.
    void measure(const Pendulum::State& x, double since_tap) {
        const double error = std::abs(x(0) - kPi);
        peak = std::max(peak, error);
        const bool still = error < 0.01 && std::abs(x(1)) < 0.05;
        if (!still) at_rest = -1.0;
        else if (at_rest < 0.0) at_rest = since_tap;
    }
};

#endif
