#include "arkita-extension-v1.h"

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <cmath>
#include <utility>

namespace {
constexpr auto panelId = "shelf_builder";
constexpr double thickness = .018;
const ArkitaExtensionHostV1 *host = nullptr;
QJsonObject form;

void *context() { return host->context; }

int copyReply(void *data, const char *json, int) {
    *static_cast<QJsonObject *>(data) = QJsonDocument::fromJson(json).object();
    return 1;
}

QJsonObject ref(const QString &key) { return {{"ref", key}}; }

void addPanel(QJsonArray &edits, const QString &key, double x0, double x1, double depth, double level, double height) {
    const auto target = ref(QStringLiteral("shelf"));
    edits.append(QJsonObject{{"type", "add_face"}, {"target", target}, {"key", key},
        {"points", QJsonArray{QJsonArray{x0, 0, level}, QJsonArray{x1, 0, level},
                              QJsonArray{x1, depth, level}, QJsonArray{x0, depth, level}}}});
    edits.append(QJsonObject{{"type", "extrude_face"}, {"target", target}, {"face", ref(key)}, {"distance", height}});
}

QJsonObject createShelf(const QJsonObject &input) {
    const auto width = input.value("width").toDouble(NAN);
    const auto height = input.value("height").toDouble(NAN);
    const auto depth = input.value("depth").toDouble(input.contains("depth") ? NAN : .3);
    const auto shelves = input.value("shelves").toInt(-1);
    if (!std::isfinite(width) || !std::isfinite(height) || !std::isfinite(depth) || width <= 2 * thickness ||
        height <= shelves * thickness || depth <= 0 || width > 20 || height > 20 || depth > 20 || shelves < 2 || shelves > 24)
        return {{"error", "invalid_shelf_dimensions"}};
    QJsonObject drawing;
    if (!host->inspect_model(context(), R"({"limit":1})", &drawing, copyReply))
        return drawing;
    if (input.contains("context") && input.value("context") != drawing.value("context"))
        return {{"error", "stale_revision"}};
    QJsonArray edits{QJsonObject{{"type", "create_definition"}, {"key", "shelf"}, {"name", QStringLiteral("Étagère")}}};
    addPanel(edits, "left", 0, thickness, depth, 0, height);
    addPanel(edits, "right", width - thickness, width, depth, 0, height);
    for (int i = 0; i < shelves; ++i) {
        const auto level = (height - thickness) * i / (shelves - 1);
        addPanel(edits, QStringLiteral("board_%1").arg(i), thickness, width - thickness, depth, level, thickness);
    }
    edits.append(QJsonObject{{"type", "insert_instance"}, {"definition", ref("shelf")}, {"key", "instance"},
        {"position", input.value("position").toArray(QJsonArray{0, 0, 0})}});
    const auto request = QJsonDocument(QJsonObject{{"context", drawing.value("context")}, {"edits", edits},
        {"label", QStringLiteral("Créer l’étagère")}}).toJson(QJsonDocument::Compact);
    QJsonObject result;
    if (!host->edit_model(context(), request.constData(), &result, copyReply))
        return result;
    const auto results = result.value("results").toArray();
    return {{"context", result.value("context")}, {"definitionId", results.first().toObject().value("id")},
            {"entityId", results.last().toObject().value("id")}};
}

void updatePanel() {
    const auto field = [](const char *key, const QString &label) {
        return QJsonObject{{"id", key}, {"label", label}, {"value", form.value(key)}};
    };
    const auto view = QJsonDocument(QJsonObject{
        {"summary", QStringLiteral("Génère un composant à l’origine du dessin. Chaque panneau fait 18 mm d’épaisseur.")},
        {"submitLabel", QStringLiteral("Créer l’étagère")}, {"submitUnchanged", true},
        {"fields", QJsonArray{field("width", "Largeur (mm)"), field("height", "Hauteur (mm)"),
                              field("depth", "Profondeur (mm)"), field("shelves", "Tablettes")}}}).toJson(QJsonDocument::Compact);
    host->update_panel(context(), panelId, view.constData());
}

void showPanel(void *) {
    updatePanel();
    host->show_panel(context(), panelId);
}

void submit(void *, const char *json) {
    const auto edited = QJsonDocument::fromJson(json).object();
    auto fields = form;
    for (auto it = edited.constBegin(); it != edited.constEnd(); ++it)
        fields.insert(it.key(), it.value());
    QJsonObject input;
    for (auto it = fields.constBegin(); it != fields.constEnd(); ++it) {
        bool valid = false;
        auto text = it.value().toString();
        const auto value = text.replace(',', '.').toDouble(&valid);
        if (valid)
            input.insert(it.key(), it.key() == "shelves" ? value : value / 1000.);
        else
            input.insert(it.key(), QJsonValue::Null);
    }
    const auto result = createShelf(input);
    if (!result.contains("error")) {
        form = std::move(fields);
        updatePanel();
        host->show_message(context(), "Étagère créée.");
        return;
    }
    const auto error = result.value("error").toString();
    const auto message = error == "invalid_shelf_dimensions" ? QStringLiteral("Vérifiez les dimensions et indiquez de 2 à 24 tablettes.")
        : QStringLiteral("L’étagère n’a pas pu être créée (%1).").arg(error);
    host->show_message(context(), message.toUtf8().constData());
}

void createMcp(void *, const char *json, void *replyContext, ArkitaMcpReplyV1 reply) {
    const auto result = createShelf(QJsonDocument::fromJson(json).object());
    const auto bytes = QJsonDocument(result).toJson(QJsonDocument::Compact);
    reply(replyContext, bytes.constData(), result.contains("error"));
}

void inspectMcp(void *, const char *json, void *replyContext, ArkitaMcpReplyV1 reply) {
    host->inspect_model(context(), json, replyContext, reply);
}

int activate(const ArkitaExtensionHostV1 *api) {
    if (!api || api->abi_version != ARKITA_EXTENSION_ABI_V1)
        return 0;
    host = api;
    form = {{"width", "900"}, {"height", "1800"}, {"depth", "300"}, {"shelves", "4"}};
    return host->register_panel(context(), panelId, "Générateur d’étagère", submit, nullptr) &&
           host->add_action(context(), "Ouvrir le générateur d’étagère", showPanel, nullptr) &&
           host->publish_mcp_tool(context(), "create_shelf", "Create a shelf component atomically. Dimensions and optional drawing-world position are in metres.",
               R"({"type":"object","properties":{"width":{"type":"number","minimum":0.036,"maximum":20},"height":{"type":"number","exclusiveMinimum":0,"maximum":20},"depth":{"type":"number","exclusiveMinimum":0,"maximum":20},"shelves":{"type":"integer","minimum":2,"maximum":24},"position":{"type":"array","items":{"type":"number"},"minItems":3,"maxItems":3},"context":{"type":"object"}},"required":["width","height","shelves"],"additionalProperties":false})",
               0, createMcp, nullptr) &&
           host->publish_mcp_tool(context(), "inspect_model", "List entities, definitions, materials or tags. Use the returned context when paging or editing.",
               R"({"type":"object","properties":{"section":{"enum":["entities","definitions","materials","tags"]},"id":{"type":"string"},"definitionId":{"type":"string"},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":128},"context":{"type":"object"}},"additionalProperties":false})",
               1, inspectMcp, nullptr);
}

void deactivate() {
    host = nullptr;
    form = {};
}

const ArkitaExtensionV1 extension{ARKITA_EXTENSION_ABI_V1, "example.shelf-builder", "Générateur d’étagère", activate, deactivate};
} // namespace

const ArkitaExtensionV1 *arkita_extension_v1(void) { return &extension; }
