// Look inside the solver: one iteration at a time, from a plan that applies no torque.
//
// An application calls solve() and reads the result. This program stops each solve before
// its line search, so that it can try every step length itself and print what each would
// cost. It uses only the solver's public interface.
#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);
    Pendulum pendulum;
    const int iterations = argc > 1 && argv[1][0] != '-' ? std::atoi(argv[1]) : 6;

    const Pendulum::State x(0.05, 0.0);
    solver.reset(x, Pendulum::Control::Zero());

    NMPC::Options<double> look;  // roll out, linearise and run the backward pass, then stop
    look.max_line_search = 0;
    look.max_regularisation_retries = 0;
    NMPC::Options<double> one;  // an ordinary solve of one iteration

    for (int iteration = 1; iteration <= iterations; iteration++) {
        // 1. Rollout: what the current plan costs from this state.
        const NMPC::Result<double> before = solver.solve(pendulum, x, look);
        if (!before.usable()) return 1;

        // 2. Backward pass: a change to every stage's torque, and the decrease it predicts.
        double linear = 0.0, quadratic = 0.0;
        int qp_passes = 0;
        if (!solver.backward(pendulum, one, linear, quadratic, qp_passes)) return 1;

        std::printf("iteration %d: the plan costs %.3f\n", iteration, before.cost_before);
        // 3. Line search: try the whole change, then half of it, then a quarter...
        bool taken = false;
        double alpha = 1.0;
        for (int trial = 0; trial < one.max_line_search; trial++, alpha *= 0.5) {
            int on_limit = 0;
            const double predicted = -(alpha * linear + alpha * alpha * quadratic);
            const double cost = solver.forward(pendulum, x, alpha, on_limit);
            const double achieved = before.cost_before - cost;
            const bool accept = !taken && predicted > 0.0 && achieved > one.accept_ratio * predicted;
            std::printf("  step %-6.4g predicted cost %8.3f, actual %8.3f  %s\n", alpha,
                        before.cost_before - predicted, cost, accept ? "accepted" : taken ? "" : "refused");
            if (trace.on()) {
                std::vector<double> row = {double(iteration), alpha, predicted, cost, double(accept), double(on_limit)};
                for (int k = 0; k < Pendulum::Stages; k++) row.push_back(solver.workspace().trial_u[k](0));
                trace.row("candidates", row);
            }
            taken = taken || accept;
        }
        if (trace.on()) {
            std::vector<double> row = {double(iteration), before.cost_before, -(linear + quadratic)};
            for (int k = 0; k < Pendulum::Stages; k++) row.push_back(solver.policy().u[k](0));
            for (int k = 0; k < Pendulum::Stages; k++) row.push_back(solver.workspace().gain[k](0, 0));
            for (int k = 0; k < Pendulum::Stages; k++) row.push_back(solver.workspace().gain[k](0, 1));
            trace.row("plans", row);
        }

        // 4. The solve itself makes the same search and keeps the first step it accepts.
        const NMPC::Result<double> after = solver.solve(pendulum, x, one);
        std::printf("  solve(): %.3f -> %.3f, %d of %d stages at the torque limit\n",
                    after.cost_before, after.cost_after, after.stages_on_bound, int(Pendulum::Stages));
        trace.row("solves", {double(iteration), after.cost_before, after.cost_after,
                             double(after.stages_on_bound), double(after.line_search_trials),
                             double(after.accepted_steps), double(after.backward_passes)});
    }
    return 0;
}
