// Thmiuler model client
// Model: Hydraulic_relief
// Solver: ode23s

#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <exception>
#include <initializer_list>
#include <limits>
#include <string>
#include <utility>
#include <vector>

#include "tecon_model_solver_api.h"

static constexpr int INPUT_COUNT = 3;
static constexpr int OUTPUT_COUNT = 4;
static constexpr int STATE_COUNT = 7;
static constexpr int PARAMETER_COUNT = 8;
static constexpr int EVENT_COUNT = 2;
static double g_time = 0.0;
static double g_step = 0.01;
static std::vector<double> g_state;
static const double* g_activeInputs = nullptr;
static int g_activeInputCount = 0;
static std::string g_lastError;
static int g_eventMode = 0;
static int g_eventCursor = 0;
static const int* g_activeEventIndices = nullptr;
static int g_activeEventIndexCount = 0;
static std::vector<double>* g_collectingEventIndicators = nullptr;
static const double g_initialState[STATE_COUNT > 0 ? STATE_COUNT : 1] = {0.8,0.0,0.0,0.0,0.0,0.0,0.0};
static std::vector<double> g_params = {0.0035,0.8,3.6,0.025,0.035,0.045,2.6,1.4};
static const char* g_parameterNames[PARAMETER_COUNT > 0 ? PARAMETER_COUNT : 1] = {"C","Gp","K","leak","tauQ","tauX","pOpen","pClose"};

/*
// ===== 用户区：开始 =====
when(s0>=pOpen+.15*u0 && s3<.5){reinit(s3,1);} when(s0<=pClose+.15*u0 && s3>.5){reinit(s3,0);}
der(s0)=(Gp*(u1-s0)-s1-leak*(s0-u2))/(60*C);
der(s1)=(K*s2*((s0-u2)/std::sqrt(std::sqrt((s0-u2)*(s0-u2)+.0001)))-s1)/tauQ;
der(s2)=(s3-s2)/tauX;
der(s3)=0;
der(s4)=(u0-s4)/0.7;
der(s5)=(u1-s5)/0.8999999999999999;
der(s6)=(u2-s6)/1.1;
// ===== 用户区：结束 =====
*/

#define E_TIME (g_time)
#define E_TIME_END (g_time + g_step)
#define der(name) d_##name
#define when(condition) if (tecon_when(static_cast<bool>(condition)))
#define reinit(name, value) tecon_reinit_##name(name, (value))

static double inputAt(const double* inputs, int count, int index) {
    return (inputs && index >= 0 && index < count) ? inputs[index] : 0.0;
}

static double& outputAt(double* outputs, int count, int index) {
    static double sink = 0.0;
    if (!outputs || index < 0 || index >= count) return sink;
    return outputs[index];
}

static double stateAt(const std::vector<double>& state, int index) {
    return (index >= 0 && index < static_cast<int>(state.size())) ? state[index] : 0.0;
}

static double& derivativeAt(std::vector<double>& dstate, int index) {
    static double sink = 0.0;
    if (index < 0 || index >= static_cast<int>(dstate.size())) return sink;
    return dstate[index];
}

static double parameterAt(int index) {
    return (index >= 0 && index < static_cast<int>(g_params.size())) ? g_params[index] : 0.0;
}

static void clearModelError() {
    g_lastError.clear();
    tecon_model_solver_clear_error();
}

static void setModelError(const std::string& message) {
    g_lastError = message;
}

static bool finiteVector(const std::vector<double>& values) {
    for (double value : values) {
        if (!std::isfinite(value)) return false;
    }
    return true;
}

static bool finiteArray(const double* values, int count) {
    if (!values || count <= 0) return true;
    for (int i = 0; i < count; ++i) {
        if (!std::isfinite(values[i])) return false;
    }
    return true;
}

static bool teconEventIndexActive(int index) {
    if (g_activeEventIndexCount <= 0 || !g_activeEventIndices) return true;
    for (int i = 0; i < g_activeEventIndexCount; ++i) {
        if (g_activeEventIndices[i] == index) return true;
    }
    return false;
}

static bool tecon_when(bool condition) {
    if (g_eventMode == 0) return false;
    const int index = g_eventCursor++;
    if (g_eventMode == 1) {
        if (g_collectingEventIndicators && index >= 0 && index < static_cast<int>(g_collectingEventIndicators->size())) {
            (*g_collectingEventIndicators)[index] = condition ? -1.0 : 1.0;
        }
        return false;
    }
    if (g_eventMode == 2) {
        return condition && teconEventIndexActive(index);
    }
    return false;
}

static void tecon_reinit_height(double& target, double value) { if (g_eventMode == 2) target = value; }
static void tecon_reinit_vel(double& target, double value) { if (g_eventMode == 2) target = value; }

struct DerivativeEquation {
    std::vector<std::pair<int, double>> terms;
    double rhs = 0.0;
};

static void addDerivativeEquation(std::vector<DerivativeEquation>& equations,
                                  std::initializer_list<std::pair<int, double>> terms,
                                  double rhs) {
    DerivativeEquation equation;
    equation.terms.assign(terms.begin(), terms.end());
    equation.rhs = rhs;
    equations.push_back(equation);
}

static void solveDerivativeEquations(const std::vector<DerivativeEquation>& equations,
                                     std::vector<double>& dstate) {
    if (equations.empty() || STATE_COUNT <= 0) return;
    std::vector<bool> touched(STATE_COUNT, false);
    for (const auto& equation : equations) {
        for (const auto& term : equation.terms) {
            if (term.first < 0 || term.first >= STATE_COUNT) continue;
            touched[term.first] = true;
        }
    }
    std::vector<int> columns;
    for (int i = 0; i < STATE_COUNT; ++i) {
        if (touched[i]) columns.push_back(i);
    }
    const int n = static_cast<int>(columns.size());
    if (n <= 0) return;

    std::vector<std::vector<double>> normal(n, std::vector<double>(n, 0.0));
    std::vector<double> rhs(n, 0.0);
    for (const auto& equation : equations) {
        std::vector<double> row(n, 0.0);
        for (const auto& term : equation.terms) {
            for (int col = 0; col < n; ++col) {
                if (columns[col] == term.first) {
                    row[col] += term.second;
                    break;
                }
            }
        }
        for (int i = 0; i < n; ++i) {
            rhs[i] += row[i] * equation.rhs;
            for (int j = 0; j < n; ++j) normal[i][j] += row[i] * row[j];
        }
    }
    double scale = 1.0;
    for (int i = 0; i < n; ++i) scale = std::max(scale, std::fabs(normal[i][i]));
    for (int i = 0; i < n; ++i) normal[i][i] += scale * 1e-12;

    for (int col = 0; col < n; ++col) {
        int pivot = col;
        double pivotAbs = std::fabs(normal[col][col]);
        for (int row = col + 1; row < n; ++row) {
            const double candidate = std::fabs(normal[row][col]);
            if (candidate > pivotAbs) {
                pivot = row;
                pivotAbs = candidate;
            }
        }
        if (pivotAbs < 1e-14) continue;
        if (pivot != col) {
            std::swap(normal[pivot], normal[col]);
            std::swap(rhs[pivot], rhs[col]);
        }
        const double divisor = normal[col][col];
        for (int j = col; j < n; ++j) normal[col][j] /= divisor;
        rhs[col] /= divisor;
        for (int row = 0; row < n; ++row) {
            if (row == col) continue;
            const double factor = normal[row][col];
            if (factor == 0.0) continue;
            for (int j = col; j < n; ++j) normal[row][j] -= factor * normal[col][j];
            rhs[row] -= factor * rhs[col];
        }
    }
    for (int i = 0; i < n; ++i) {
        if (std::isfinite(rhs[i])) dstate[columns[i]] = rhs[i];
    }
}



// ===== 全局区：开始 =====
// 写全局变量、全局常量、#include 和辅助函数。
// ===== 全局区：结束 =====

static void ensureState() {
    if (g_state.size() != STATE_COUNT) g_state.assign(g_initialState, g_initialState + STATE_COUNT);
    if (g_params.size() != PARAMETER_COUNT) g_params.resize(PARAMETER_COUNT, 0.0);
}

static void tecon_reinit_s0(double&v,double x){if(g_eventMode==2)v=x;}
static void tecon_reinit_s1(double&v,double x){if(g_eventMode==2)v=x;}
static void tecon_reinit_s2(double&v,double x){if(g_eventMode==2)v=x;}
static void tecon_reinit_s3(double&v,double x){if(g_eventMode==2)v=x;}
static void tecon_reinit_s4(double&v,double x){if(g_eventMode==2)v=x;}
static void tecon_reinit_s5(double&v,double x){if(g_eventMode==2)v=x;}
static void tecon_reinit_s6(double&v,double x){if(g_eventMode==2)v=x;}
static void userModel(double t,const double*inputs,int inputCount,const std::vector<double>&state,
std::vector<double>&dstate,double*outputs,int outputCount,std::vector<double>*stateWriteback=nullptr){
std::fill(dstate.begin(),dstate.end(),0.0);double s0=state[0];double&d_s0=dstate[0];
double s1=state[1];double&d_s1=dstate[1];
double s2=state[2];double&d_s2=dstate[2];
double s3=state[3];double&d_s3=dstate[3];
double s4=state[4];double&d_s4=dstate[4];
double s5=state[5];double&d_s5=dstate[5];
double s6=state[6];double&d_s6=dstate[6];
const double u0=inputAt(inputs,inputCount,0);
const double u1=inputAt(inputs,inputCount,1);
const double u2=inputAt(inputs,inputCount,2);
const double C=parameterAt(0);
const double Gp=parameterAt(1);
const double K=parameterAt(2);
const double leak=parameterAt(3);
const double tauQ=parameterAt(4);
const double tauX=parameterAt(5);
const double pOpen=parameterAt(6);
const double pClose=parameterAt(7);
when(s0>=pOpen+.15*u0 && s3<.5){reinit(s3,1);} when(s0<=pClose+.15*u0 && s3>.5){reinit(s3,0);}
der(s0)=(Gp*(u1-s0)-s1-leak*(s0-u2))/(60*C);
der(s1)=(K*s2*((s0-u2)/std::sqrt(std::sqrt((s0-u2)*(s0-u2)+.0001)))-s1)/tauQ;
der(s2)=(s3-s2)/tauX;
der(s3)=0;
der(s4)=(u0-s4)/0.7;
der(s5)=(u1-s5)/0.8999999999999999;
der(s6)=(u2-s6)/1.1;
for(double&v:dstate)v/=(1.0+1e-12);if(stateWriteback)(*stateWriteback)[0]=s0;
if(stateWriteback)(*stateWriteback)[1]=s1;
if(stateWriteback)(*stateWriteback)[2]=s2;
if(stateWriteback)(*stateWriteback)[3]=s3;
if(stateWriteback)(*stateWriteback)[4]=s4;
if(stateWriteback)(*stateWriteback)[5]=s5;
if(stateWriteback)(*stateWriteback)[6]=s6;
}
static void modelDerivativeCallback(double t,
                                    const double* state,
                                    int stateCount,
                                    double* derivative,
                                    void*) {
    const std::vector<double> stateVector(state, state + stateCount);
    std::vector<double> dstate(STATE_COUNT, 0.0);
    double scratch[OUTPUT_COUNT > 0 ? OUTPUT_COUNT : 1] = {};
    userModel(t, g_activeInputs, g_activeInputCount, stateVector, dstate, scratch, OUTPUT_COUNT);
    for (int i = 0; i < STATE_COUNT && i < stateCount; ++i) derivative[i] = dstate[i];
}

static int collectModelEventIndicators(double currentTime,
                                       const double* inputs,
                                       int inputCount,
                                       const double* state,
                                       int stateCount,
                                       std::vector<double>& indicators) {
    indicators.assign(EVENT_COUNT, 1.0);
    if (EVENT_COUNT <= 0) return 1;
    if (STATE_COUNT > 0 && (!state || stateCount < STATE_COUNT)) {
        setModelError("event indicator state buffer mismatch");
        return 0;
    }
    std::vector<double> stateVector(STATE_COUNT, 0.0);
    for (int i = 0; i < STATE_COUNT; ++i) stateVector[i] = state[i];
    std::vector<double> dstate(STATE_COUNT, 0.0);
    double scratch[OUTPUT_COUNT > 0 ? OUTPUT_COUNT : 1] = {};
    const double oldTime = g_time;
    const int oldMode = g_eventMode;
    g_time = currentTime;
    g_eventMode = 1;
    g_eventCursor = 0;
    g_collectingEventIndicators = &indicators;
    g_activeEventIndices = nullptr;
    g_activeEventIndexCount = 0;
    try {
        userModel(currentTime, inputs, inputCount, stateVector, dstate, scratch, OUTPUT_COUNT);
    } catch (const std::exception& ex) {
        setModelError(std::string("event indicator exception: ") + ex.what());
        g_collectingEventIndicators = nullptr;
        g_eventMode = oldMode;
        g_time = oldTime;
        return 0;
    } catch (...) {
        setModelError("event indicator unknown exception");
        g_collectingEventIndicators = nullptr;
        g_eventMode = oldMode;
        g_time = oldTime;
        return 0;
    }
    g_collectingEventIndicators = nullptr;
    g_eventMode = oldMode;
    g_time = oldTime;
    return finiteVector(indicators) ? 1 : 0;
}

static int applyModelEvents(double currentTime,
                            const double* inputs,
                            int inputCount,
                            double* state,
                            int stateCount,
                            const int* eventIndices,
                            int eventCount) {
    if (EVENT_COUNT <= 0) return 1;
    if (STATE_COUNT > 0 && (!state || stateCount < STATE_COUNT)) {
        setModelError("event reinit state buffer mismatch");
        return 0;
    }
    std::vector<double> stateVector(STATE_COUNT, 0.0);
    for (int i = 0; i < STATE_COUNT; ++i) stateVector[i] = state[i];
    std::vector<double> dstate(STATE_COUNT, 0.0);
    double scratch[OUTPUT_COUNT > 0 ? OUTPUT_COUNT : 1] = {};
    const double oldTime = g_time;
    const int oldMode = g_eventMode;
    g_time = currentTime;
    g_eventMode = 2;
    g_eventCursor = 0;
    g_collectingEventIndicators = nullptr;
    g_activeEventIndices = eventIndices;
    g_activeEventIndexCount = eventCount;
    try {
        userModel(currentTime, inputs, inputCount, stateVector, dstate, scratch, OUTPUT_COUNT, &stateVector);
    } catch (const std::exception& ex) {
        setModelError(std::string("event reinit exception: ") + ex.what());
        g_activeEventIndices = nullptr;
        g_activeEventIndexCount = 0;
        g_eventMode = oldMode;
        g_time = oldTime;
        return 0;
    } catch (...) {
        setModelError("event reinit unknown exception");
        g_activeEventIndices = nullptr;
        g_activeEventIndexCount = 0;
        g_eventMode = oldMode;
        g_time = oldTime;
        return 0;
    }
    g_activeEventIndices = nullptr;
    g_activeEventIndexCount = 0;
    g_eventMode = oldMode;
    g_time = oldTime;
    if (!finiteVector(stateVector)) {
        setModelError("event reinit produced NaN or Inf");
        return 0;
    }
    for (int i = 0; i < STATE_COUNT; ++i) state[i] = stateVector[i];
    return 1;
}

static void modelEventIndicatorCallback(double t,
                                        const double* state,
                                        int stateCount,
                                        double* indicators,
                                        int indicatorCount,
                                        void*) {
    if (!indicators || indicatorCount <= 0) return;
    std::vector<double> localIndicators;
    if (!collectModelEventIndicators(t, g_activeInputs, g_activeInputCount, state, stateCount, localIndicators)) {
        std::fill(indicators, indicators + indicatorCount, std::numeric_limits<double>::quiet_NaN());
        return;
    }
    for (int i = 0; i < indicatorCount; ++i) {
        indicators[i] = i < static_cast<int>(localIndicators.size()) ? localIndicators[i] : 1.0;
    }
}

static int modelEventApplyCallback(double t,
                                   double* state,
                                   int stateCount,
                                   const int* eventIndices,
                                   int eventCount,
                                   void*) {
    return applyModelEvents(t, g_activeInputs, g_activeInputCount, state, stateCount, eventIndices, eventCount);
}

extern "C" __declspec(dllexport) int tecon_model_initial_state(double* state, int stateCount) {
    ensureState();
    if (STATE_COUNT <= 0) return 1;
    if (!state || stateCount < STATE_COUNT) return 0;
    for (int i = 0; i < STATE_COUNT; ++i) state[i] = g_initialState[i];
    return 1;
}

extern "C" __declspec(dllexport) void tecon_model_set_state(const double* state, int stateCount) {
    ensureState();
    if (!state || stateCount < STATE_COUNT) return;
    for (int i = 0; i < STATE_COUNT; ++i) g_state[i] = state[i];
}

extern "C" __declspec(dllexport) int tecon_model_evaluate(double currentTime,
                                                           const double* inputs,
                                                           int inputCount,
                                                           double* state,
                                                           int stateCount,
                                                           double* derivatives,
                                                           int derivativeCount,
                                                           double* outputs,
                                                           int outputCount,
                                                           int allowStateWriteback) {
    clearModelError();
    ensureState();
    if (outputs && outputCount > 0) std::fill(outputs, outputs + outputCount, 0.0);
    if (STATE_COUNT > 0 && (!state || stateCount < STATE_COUNT || !derivatives || derivativeCount < STATE_COUNT)) {
        setModelError("model evaluate state buffer mismatch");
        return 0;
    }
    if (!finiteArray(inputs, inputCount)) {
        setModelError("model evaluate input contains NaN or Inf");
        return 0;
    }
    std::vector<double> stateVector(STATE_COUNT, 0.0);
    for (int i = 0; i < STATE_COUNT; ++i) stateVector[i] = state[i];
    std::vector<double> dstate(STATE_COUNT, 0.0);
    const double oldTime = g_time;
    g_time = currentTime;
    try {
        userModel(currentTime,
                  inputs,
                  inputCount,
                  stateVector,
                  dstate,
                  outputs,
                  outputCount,
                  allowStateWriteback ? &stateVector : nullptr);
    } catch (const std::exception& ex) {
        setModelError(std::string("user model evaluate exception: ") + ex.what());
        g_time = oldTime;
        return 0;
    } catch (...) {
        setModelError("user model evaluate unknown exception");
        g_time = oldTime;
        return 0;
    }
    if (!finiteVector(dstate) || !finiteVector(stateVector)) {
        setModelError("model evaluate state or derivative contains NaN or Inf");
        g_time = oldTime;
        return 0;
    }
    for (int i = 0; i < STATE_COUNT; ++i) {
        derivatives[i] = dstate[i];
        if (allowStateWriteback) state[i] = stateVector[i];
    }
    outputAt(outputs, outputCount, 0) = stateAt(stateVector, 0);
    outputAt(outputs, outputCount, 1) = stateAt(stateVector, 1);
    outputAt(outputs,outputCount,2)=stateAt(stateVector,2);
    outputAt(outputs,outputCount,3)=stateAt(stateVector,3);
    if (!finiteArray(outputs, outputCount)) {
        setModelError("model evaluate output contains NaN or Inf");
        g_time = oldTime;
        return 0;
    }
    g_time = oldTime;
    return 1;
}



extern "C" __declspec(dllexport) int tecon_model_event_indicator_count() {
    return EVENT_COUNT;
}

extern "C" __declspec(dllexport) int tecon_model_event_indicators(double currentTime,
                                                                   const double* inputs,
                                                                   int inputCount,
                                                                   const double* state,
                                                                   int stateCount,
                                                                   double* indicators,
                                                                   int indicatorCount) {
    clearModelError();
    ensureState();
    if (!indicators || indicatorCount < EVENT_COUNT) {
        setModelError("event indicator buffer mismatch");
        return 0;
    }
    std::vector<double> localIndicators;
    if (!collectModelEventIndicators(currentTime, inputs, inputCount, state, stateCount, localIndicators)) return 0;
    for (int i = 0; i < indicatorCount; ++i) {
        indicators[i] = i < static_cast<int>(localIndicators.size()) ? localIndicators[i] : 1.0;
    }
    return 1;
}

extern "C" __declspec(dllexport) int tecon_model_apply_events(double currentTime,
                                                               const double* inputs,
                                                               int inputCount,
                                                               double* state,
                                                               int stateCount,
                                                               const int* eventIndices,
                                                               int eventCount) {
    clearModelError();
    ensureState();
    return applyModelEvents(currentTime, inputs, inputCount, state, stateCount, eventIndices, eventCount);
}

static void integrate(const double* inputs, int inputCount) {
    if (STATE_COUNT <= 0 || g_step <= 0.0) return;
    g_activeInputs = inputs;
    g_activeInputCount = inputCount;
    const double t0 = E_TIME;
    const double tend = E_TIME_END;
    std::vector<double> result = g_state;
    TeconModelSolverOptions options;
    options.solverName = "ode23s";
    options.tolerance = 1e-6;
    options.maxIterations = 6;
    options.minStep = 0.0;
    options.maxStep = 0.0;
    if (!finiteVector(g_state)) {
        setModelError("状态初始值包含 NaN 或 Inf");
        g_activeInputs = nullptr;
        g_activeInputCount = 0;
        return;
    }
    const int ok = EVENT_COUNT > 0
                       ? tecon_model_solver_integrate_events(&options,
                                                             modelDerivativeCallback,
                                                             nullptr,
                                                             modelEventIndicatorCallback,
                                                             modelEventApplyCallback,
                                                             nullptr,
                                                             EVENT_COUNT,
                                                             g_state.data(),
                                                             STATE_COUNT,
                                                             t0,
                                                             g_step,
                                                             tend,
                                                             result.data())
                       : tecon_model_solver_integrate(&options,
                                                      modelDerivativeCallback,
                                                      nullptr,
                                                      g_state.data(),
                                                      STATE_COUNT,
                                                      t0,
                                                      g_step,
                                                      tend,
                                                      result.data());
    if (ok) {
        g_state = result;
    } else {
        const char* error = tecon_model_solver_last_error();
        setModelError(error && *error ? error : "求解器积分失败");
    }
    g_activeInputs = nullptr;
    g_activeInputCount = 0;
}

extern "C" __declspec(dllexport) void tecon_set_time(double currentTime) { g_time = currentTime; }
extern "C" __declspec(dllexport) void tecon_set_step(double stepSize) { g_step = stepSize; }
extern "C" __declspec(dllexport) void tecon_reset() { clearModelError(); g_state.clear(); ensureState(); }
extern "C" __declspec(dllexport) void tecon_stop() {}
extern "C" __declspec(dllexport) int tecon_input_count() { return INPUT_COUNT; }
extern "C" __declspec(dllexport) int tecon_output_count() { return OUTPUT_COUNT; }
extern "C" __declspec(dllexport) int tecon_state_count() { return STATE_COUNT; }
extern "C" __declspec(dllexport) int tecon_parameter_count() { return PARAMETER_COUNT; }
extern "C" __declspec(dllexport) const char* tecon_parameter_name(int index) {
    return (index >= 0 && index < PARAMETER_COUNT) ? g_parameterNames[index] : "";
}
extern "C" __declspec(dllexport) double tecon_parameter_value(int index) {
    return parameterAt(index);
}
extern "C" __declspec(dllexport) void tecon_set_parameter(int index, double value) {
    ensureState();
    if (index >= 0 && index < static_cast<int>(g_params.size())) g_params[index] = value;
}
extern "C" __declspec(dllexport) const char* tecon_solver_name() { return "ode23s"; }
extern "C" __declspec(dllexport) const char* tecon_last_error() { return g_lastError.c_str(); }

extern "C" __declspec(dllexport) void tecon_step(const double* inputs, int inputCount, double* outputs, int outputCount) {
    clearModelError();
    ensureState();
    if (outputs && outputCount > 0) std::fill(outputs, outputs + outputCount, 0.0);
    integrate(inputs, inputCount);
    if (!g_lastError.empty()) return;
    std::vector<double> dstate(STATE_COUNT, 0.0);
    try {
        userModel(E_TIME_END, inputs, inputCount, g_state, dstate, outputs, outputCount, &g_state);
    } catch (const std::exception& ex) {
        setModelError(std::string("用户模型输出计算异常: ") + ex.what());
        return;
    } catch (...) {
        setModelError("用户模型输出计算发生未知异常");
        return;
    }
    if (!finiteVector(g_state)) {
        setModelError("用户模型状态写回包含 NaN 或 Inf");
        return;
    }
    if (!finiteArray(outputs, outputCount)) {
        setModelError("用户模型输出包含 NaN 或 Inf");
        return;
    }
    outputAt(outputs, outputCount, 0) = stateAt(g_state, 0);
    outputAt(outputs, outputCount, 1) = stateAt(g_state, 1);
}
