
// Created by Calvin Chau on 06.05.25.
//
// This file is taken and modified from
// https://github.com/moves-rwth/storm/blob/master/src/storm/modelchecker/multiobjective/pcaa/SparsePcaaAchievabilityQuery.cpp

#include "CustomAchievabilityQuery.h"


template<typename ValueType, typename CertValueType>
CustomAchievabilityQuery<ValueType, CertValueType>::CustomAchievabilityQuery(
    storm::modelchecker::multiobjective::preprocessing::SparseMultiObjectivePreprocessorResult<StormMdp<ValueType> > &
    preprocessorResult, std::shared_ptr<ReachabilityForm<ValueType> > rf, ReachabilityQuery query)
    : storm::modelchecker::multiobjective::SparsePcaaQuery<StormMdp<ValueType>,
          storm::RationalNumber>(preprocessorResult), rf(rf), query(query) {
    spdlog::debug("Resetting");
    this->weightVectorChecker.reset();
    spdlog::debug("done Resetting");
    this->weightVectorChecker = std::make_unique<CustomWeightChecker<ValueType> >(preprocessorResult);
    spdlog::debug("casting");
    customChecker = dynamic_cast<CustomWeightChecker<ValueType> *>(this->weightVectorChecker.get());
    spdlog::debug("done casting");

    initializeThresholdData();

    // Set the precision of the weight vector checker. Will be refined during the computation
    this->weightVectorChecker->setWeightedPrecision(
        storm::utility::convertNumber<typename StormMdp<ValueType>::ValueType>(0.1));
}

template<typename ValueType, typename CertValueType>
void CustomAchievabilityQuery<ValueType, CertValueType>::initializeThresholdData() {
    thresholds.reserve(this->objectives.size());
    strictThresholds = storm::storage::BitVector(this->objectives.size(), false);
    for (uint_fast64_t objIndex = 0; objIndex < this->objectives.size(); ++objIndex) {
        auto const &formula = *this->objectives[objIndex].formula;
        STORM_LOG_ASSERT(formula.hasBound(), "Achievability query invoked but there is an objective without bound.");
        thresholds.push_back(formula.template getThresholdAs<storm::RationalNumber>());
        if (storm::solver::minimize(formula.getOptimalityType())) {
            STORM_LOG_ASSERT(!storm::logic::isLowerBound(formula.getBound().comparisonType),
                             "Minimizing objective should not specify an upper bound.");
            // Values for minimizing objectives will be negated in order to convert them to maximizing objectives.
            // Hence, we also negate the threshold
            thresholds.back() *= -storm::utility::one<storm::RationalNumber>();
        }
        strictThresholds.set(objIndex, storm::logic::isStrict(formula.getBound().comparisonType));
    }
}

template<typename ValueType, typename CertValueType>
std::unique_ptr<storm::modelchecker::CheckResult> CustomAchievabilityQuery<ValueType, CertValueType>::check(
    storm::Environment const &env) {
    bool result = this->checkAchievability(env);
    return std::unique_ptr<storm::modelchecker::CheckResult>(
        new storm::modelchecker::ExplicitQualitativeCheckResult(
            this->originalModel.getInitialStates().getNextSetIndex(0), result));
}

template<typename ValueType, typename CertValueType>
std::vector<CertValueType> CustomAchievabilityQuery<ValueType, CertValueType>::getWeightVector() {
    if constexpr (std::is_same_v<CertValueType, double>) {
        std::vector<double> weightVector;
        for (const auto &weight: this->refinementSteps.back().weightVector) {
            weightVector.push_back(weight.get_d());
        }
        return weightVector;
    } else {
        return this->refinementSteps.back().weightVector;
    }
}

template<typename ValueType, typename CertValueType>
std::vector<std::pair<CertValueType, storm::storage::Scheduler<ValueType>>> CustomAchievabilityQuery<ValueType, CertValueType>::getWeightedSchedulers() {
    assert(this->refinementSteps.size() == schedulers.size());
    spdlog::debug("Starting to compute weights for schedulers. There are {} scheduler(s)", schedulers.size());
    // For each scheduler, added a continuous nonnegative variable representing the probability with which it is chosen
    //auto solver = storm::utility::solver::getRawLpSolver<CertValueType>("solver");
    auto solver = storm::utility::solver::GurobiLpSolverFactory<CertValueType>().createRaw("solver");
    for (uint_fast64_t schedulerIndex = 0; schedulerIndex < schedulers.size(); schedulerIndex++) {
        solver->addContinuousVariable("a", storm::utility::zero<CertValueType>(),
                                      storm::utility::one<CertValueType>());
    }
    const uint_fast64_t slackVariable = schedulers.size();
    solver->addContinuousVariable("slack", storm::utility::zero<CertValueType>(),
                                  storm::utility::one<CertValueType>(),
                                  storm::utility::one<CertValueType>());

    // Add constraint that ensure that we have a convex combination
    auto convexityConstraint = storm::solver::RawLpConstraint<CertValueType>(
        storm::expressions::RelationType::Equal, storm::utility::one<CertValueType>());
    for (uint_fast64_t schedulerIndex = 0; schedulerIndex < schedulers.size(); schedulerIndex++) {
        auto coefficient = storm::utility::one<CertValueType>();
        convexityConstraint.addToLhs(schedulerIndex, coefficient);
    }
    solver->addConstraint("convexity constraint", convexityConstraint);

    // For each objective add a threshold constraint
    std::vector<storm::solver::RawLpConstraint<CertValueType> > thresholdConstraints;
    for (uint_fast64_t targetIndex = 0; targetIndex < query.getNumTargetSets(); targetIndex++) {
        auto relationType = query.hasLowerBounds()
                                ? storm::expressions::RelationType::GreaterOrEqual
                                : storm::expressions::RelationType::LessOrEqual;
        if constexpr (std::is_same_v<CertValueType, double>) {
            thresholdConstraints.emplace_back(relationType, query.getBounds()[targetIndex].get_d());
        }
        else {
            thresholdConstraints.emplace_back(relationType, query.getBounds()[targetIndex]);
        }
        if (query.hasStrictBounds()) {
            thresholdConstraints.back().addToLhs(slackVariable,
                                                 query.hasLowerBounds()
                                                     ? -storm::utility::one<CertValueType>()
                                                     : storm::utility::one<CertValueType>());
        }
    }
    for (uint_fast64_t schedulerIndex = 0; schedulerIndex < schedulers.size(); schedulerIndex++) {
        for (uint_fast64_t targetIndex = 0; targetIndex < query.getNumTargetSets(); targetIndex++) {
            auto step = this->refinementSteps[schedulerIndex];
            auto coefficient = query.hasLowerBounds()
                                   ? step.lowerBoundPoint[targetIndex]
                                   : step.upperBoundPoint[targetIndex];
            std::cout << schedulerIndex << ": " << coefficient.get_d() << std::endl;
            if constexpr (std::is_same_v<CertValueType, double>) {
                thresholdConstraints[targetIndex].addToLhs(schedulerIndex, coefficient.get_d());
            }
            else {
                thresholdConstraints[targetIndex].addToLhs(schedulerIndex, coefficient);
            }
        }
    }
    for (const auto &thresholdConstraint: thresholdConstraints) {
        solver->addConstraint("threshold constraint", thresholdConstraint);
    }
    spdlog::debug("Built constraints");

    // Optimize linear program
    solver->optimize();
    spdlog::debug("Optimized LP");
    if (solver->isInfeasible()) {
        throw std::runtime_error("Cannot compute weights! Infeasible!");
    }
    if (solver->isUnbounded()) {
        throw std::runtime_error("Cannot compute weights! Unbounded!");
    }
    if (solver->isOptimal()) {
        if (query.hasStrictBounds() && solver->getContinuousValue(slackVariable) == storm::utility::zero<ValueType>()) {
            throw std::runtime_error("Cannot compute weights! Strict bounds not satisfied!");
        }
    }

    std::vector<std::pair<CertValueType, storm::storage::Scheduler<ValueType>>> weightedSchedulers;
    // for (uint_fast64_t schedulerIndex = 0; schedulerIndex < schedulers.size(); schedulerIndex++) {
    //     // Construct scheduler for original reachability form
    //     storm::storage::Scheduler<ValueType> scheduler(rf->getNumberOfStates());
    //     const storm::storage::BitVector& maybeStates = this->customChecker->getMaybeStates();
    //     assert(maybeStates.size() == rf->getNumberOfStates());
    //     for (auto state : rf->getStates().asIntegerRange()) {
    //         if (maybeStates.get(state)) {
    //             auto choice = schedulers[schedulerIndex].getChoice(customChecker->getNewState(state));
    //             if (choice.isDefined()) {
    //                 scheduler.setChoice(choice, state);
    //             }
    //             else {
    //                 scheduler.setDontCare(state);
    //             }
    //         }
    //         else {
    //             scheduler.setDontCare(state);
    //         }
    //     }
    //     assert(!scheduler.isPartialScheduler());
    //     weightedSchedulers.emplace_back(solver->getContinuousValue(schedulerIndex), scheduler);
    // }
    //
    // spdlog::debug("Computed weights for schedulers");
    //
    return weightedSchedulers;
}

template<typename ValueType, typename CertValueType>
bool CustomAchievabilityQuery<ValueType, CertValueType>::checkAchievability(storm::Environment const &env) {
    // repeatedly refine the over/ under approximation until the threshold point is either in the under approx. or not in the over approx.
    while (!this->maxStepsPerformed(env) && !storm::utility::resources::isTerminate()) {
        WeightVector separatingVector = this->findSeparatingVector(thresholds);
        this->updateWeightedPrecision(separatingVector);
        this->performRefinementStep(env, std::move(separatingVector));
        schedulers.push_back(this->weightVectorChecker->computeScheduler());
        if (!checkIfThresholdsAreSatisfied(this->overApproximation)) {
            return false;
        }
        if (checkIfThresholdsAreSatisfied(this->underApproximation)) {
            return true;
        }
    }
    STORM_LOG_ERROR(
        "Could not check whether thresholds are achievable: Termination requested or maximum number of refinement steps exceeded.")
    ;
    return false;
}

template<typename ValueType, typename CertValueType>
void CustomAchievabilityQuery<ValueType, CertValueType>::updateWeightedPrecision(WeightVector const &weights) {
    // Our heuristic considers the distance between the under- and the over approximation w.r.t. the given direction
    std::pair<Point, bool> optimizationResOverApprox = this->overApproximation->optimize(weights);
    if (optimizationResOverApprox.second) {
        std::pair<Point, bool> optimizationResUnderApprox = this->underApproximation->optimize(weights);
        if (optimizationResUnderApprox.second) {
            storm::RationalNumber distance = storm::utility::vector::dotProduct(
                                                 optimizationResOverApprox.first, weights) -
                                             storm::utility::vector::dotProduct(
                                                 optimizationResUnderApprox.first, weights);
            STORM_LOG_ASSERT(distance >= storm::utility::zero<storm::RationalNumber>(),
                             "Negative distance between under- and over approximation was not expected");
            // Normalize the distance by dividing it with the Euclidean Norm of the weight-vector
            distance /= storm::utility::sqrt(storm::utility::vector::dotProduct(weights, weights));
            distance /= storm::RationalNumber(2);
            this->weightVectorChecker->setWeightedPrecision(storm::utility::convertNumber<ValueType>(distance));
        }
    }
    // do not update the precision if one of the approximations is unbounded in the provided direction
}

template<typename ValueType, typename CertValueType>
bool CustomAchievabilityQuery<ValueType, CertValueType>::checkIfThresholdsAreSatisfied(
    std::shared_ptr<storm::storage::geometry::Polytope<storm::RationalNumber> > const &polytope) {
    std::vector<storm::storage::geometry::Halfspace<storm::RationalNumber> > halfspaces = polytope->getHalfspaces();
    for (auto const &h: halfspaces) {
        if (storm::utility::isZero(h.distance(thresholds))) {
            // Check if the threshold point is on the boundary of the halfspace and whether this is violates strict thresholds
            if (h.isPointOnBoundary(thresholds)) {
                for (auto strictThreshold: strictThresholds) {
                    if (h.normalVector()[strictThreshold] > storm::utility::zero<storm::RationalNumber>()) {
                        return false;
                    }
                }
            }
        } else {
            return false;
        }
    }
    return true;
}

template class CustomAchievabilityQuery<double, double>;
template class CustomAchievabilityQuery<double, storm::RationalNumber>;
template class CustomAchievabilityQuery<storm::RationalNumber, storm::RationalNumber>;
