#include <epictuner/sdk/plugin.hpp>
#include <optional>

class Lifecycle : public et::sdk::Plugin {
    std::optional<et::sdk::Context> context_;
public:
    static constexpr std::string_view id = "org.epictuner.examples.lifecycle";
    static constexpr uint64_t capabilities = ET_CAP_LOG | ET_CAP_EVENTS;
    et_result start(et::sdk::Context& context)
    {
        context_ = context;
        et_context_service service {};
        const auto found = context.service(ET_SERVICE_CONTEXT, ET_SERVICE_VERSION_1, &service, sizeof(service));
        if (found == ET_OK) {
            et_limits limits {}; limits.struct_size = sizeof(limits);
            et_feature_info feature {}; feature.struct_size = sizeof(feature);
            if (service.get_limits(service.context, &limits) != ET_OK
                || limits.pending_requests != ET_MAX_PENDING_REQUESTS
                || service.get_feature(service.context, et::sdk::string("et.context.v1"), &feature) != ET_OK
                || !(feature.flags & ET_FEATURE_AVAILABLE)) return ET_ERROR_STATE;
        } else if (found != ET_ERROR_UNSUPPORTED) return found;
        return context_->log("C++ plugin started");
    }
    et_result onEvent(const et_event& event)
    {
        if (event.type != ET_EVENT_MESSAGE) return ET_ERROR_UNSUPPORTED;
        return context_->log(std::string_view(event.text.data, event.text.size));
    }
    et_result stop() { return context_->log("C++ plugin stopped"); }
};
ET_PLUGIN(Lifecycle)
